Explain the terms body-parser, cookie-parser, morgan, nodemon, pm2, serve-favicon, cors, dotenv, fs-extra, moment in Express JS?
Explain the terms body-parser, cookie-parser, morgan, nodemon, pm2, serve-favicon, cors, dotenv, fs-extra, moment in Express JS?
a) body-parser
body-parserextract the entire body portion of an incoming request stream and exposes it onreq.body. This body-parser module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST request.Example:
npm install express ejs body-parser// server.js var express = require('express') var bodyParser = require('body-parser') var app = express() // create application/json parser var jsonParser = bodyParser.json() // create application/x-www-form-urlencoded parser var urlencodedParser = bodyParser.urlencoded({ extended: false }) // POST /login gets urlencoded bodies app.post('/login', urlencodedParser, function (req, res) { res.send('welcome, ' + req.body.username) }) // POST /api/users gets JSON bodies app.post('/api/users', jsonParser, function (req, res) { // create user in req.body })b) cookie-parser
A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using.
The
cookie-parsermiddleware's cookieParser function takes asecretstring or array of strings as the first argument and anoptionsobject as the second argument.Installation
npm install cookie-parserExample:
var express = require('express') var cookieParser = require('cookie-parser') var app = express() app.use(cookieParser()) app.get('/', function (req, res) { // Cookies that have not been signed console.log('Cookies: ', req.cookies) // Cookies that have been signed console.log('Signed Cookies: ', req.signedCookies) }) app.listen(3000)c) morgan
HTTP request logger middleware for node.js.
Installation
npm install morganExample: write logs to a file
var express = require('express') var fs = require('fs') var morgan = require('morgan') var path = require('path') var app = express() // create a write stream (in append mode) var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) // setup the logger app.use(morgan('combined', { stream: accessLogStream })) app.get('/', function (req, res) { res.send('hello, world!') })d) nodemon
Nodemon is a utility that will monitor for any changes in source and automatically restart your server.
Installation
npm install -g nodemonExample:
{ // ... "scripts": { "start": "nodemon server.js" }, // ... }e) pm2
P(rocess) M(anager) 2 (pm2) is a production process manager for Node.js applications with a built-in load balancer. It allows to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.
Installation
npm install pm2 -gStart an application
pm2 start app.jsf) serve-favicon
Node.js middleware for serving a favicon. The
serve-faviconmodule lets us exclude requests for the favicon in our logger middleware. It also caches the icon in memory to improve performance by reducing disk access. In addition, it provides anETagbased on the contents of the icon, rather than file system properties.Installation
npm install serve-faviconExample:
var express = require('express') var favicon = require('serve-favicon') var path = require('path') var app = express() app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))) // Add your routes here, etc. app.listen(3000)g) cors
Cross-Origin Resource Sharing (CORS) headers allow apps running in the browser to make requests to servers on different domains (also known as origins). CORS headers are set on the server side - the HTTP server is responsible for indicating that a given HTTP request can be cross-origin. CORS defines a way in which a browser and server can interact and determine whether or not it is safe to allow a cross-origin request.
Installation
npm install corsExample: Enable All CORS Requests
var express = require('express') var cors = require('cors') var app = express() app.use(cors()) app.get('/products/:id', function (req, res, next) { res.json({msg: 'This is CORS-enabled for all origins!'}) }) app.listen(8080, function () { console.log('CORS-enabled web server listening on port 80') })Example: Enable CORS for a Single Route
var express = require('express') var cors = require('cors') var app = express() app.get('/products/:id', cors(), function (req, res, next) { res.json({msg: 'This is CORS-enabled for a Single Route'}) }) app.listen(8080, function () { console.log('CORS-enabled web server listening on port 80') })h) dotenv
When a NodeJs application runs, it injects a global variable called
process.envwhich contains information about the state of environment in which the application is running. Thedotenvloads environment variables stored in the.envfile intoprocess.env.Installation
npm install dotenvUsage
// .env DB_HOST=localhost DB_USER=admin DB_PASS=root// config.js const db = require('db') db.connect({ host: process.env.DB_HOST, username: process.env.DB_USER, password: process.env.DB_PASS })i) fs-extra
fs-extracontains methods that aren't included in the vanilla Node.js fs package. Such as recursivemkdir,copy, andremove. It also uses graceful-fs to preventEMFILEerrors.Installation
npm install fs-extraUsage
const fs = require('fs-extra') // Async with callbacks: fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { if (err) return console.error(err) console.log('success!') })j) moment
A JavaScript date library for parsing, validating, manipulating, and formatting dates.
Installation:
npm install moment --saveUsage:
- Format Dates
const moment = require('moment');
moment().format('MMMM Do YYYY, h:mm:ss a'); // October 24th 2020, 3:15:22 pm
moment().format('dddd'); // Saturday
moment().format("MMM Do YY"); // Oct 24th 20- Relative Time
const moment = require('moment');
moment("20111031", "YYYYMMDD").fromNow(); // 9 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 8 years ago
moment().startOf('day').fromNow(); // 15 hours ago- Calendar Time
const moment = require('moment');
moment().subtract(10, 'days').calendar(); // 10/14/2020
moment().subtract(6, 'days').calendar(); // Last Sunday at 3:18 PM
moment().subtract(3, 'days').calendar(); // Last Wednesday at 3:18 PM
0 Comments