Required NPM Packages

Throughout our examples, some required npm packages need to be installed, some of them can be installed by npm – build-in package management tool, and the remaining are bundled with Node.js . Please find the below packages and their details:

Package Express
NPM Install npm install express
Functions Provide the coding framework
Usage Create the URL routing by:

 

var express         = require(‘express’);

var router            = express.Router();

//define the controller’s method and map the request URL ‘/’ to this method

router.get(‘/’, function(req, res)

 

Package body-parser
NPM Install npm install body-parser
Functions Being a middleware to extract incoming request, in order to parse POST data from req.body .
Usage var bodyParser = require(‘body-parser’);

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

//Getting parameters values from req.body

var customer = new Customer(0, req.body.firstname, req.body.lastname, req.body.telephone, req.body.email, req.body.age, req.body.gender, req.body.username, req.body.password);

 

Package ejs
NPM Install npm install ejs
Functions Providing template feature
Usage //Define the template path, and tell Node.js that it is using ejs as view engine

app.set(‘views’, __dirname + ‘/app/views’);

app.set(‘view engine’, ‘ejs’);

//Output the results to related ejs template

res.render(‘customer/new‘, { title: ‘New Customer’, msgType: ”, msg: ”, customer: customer});

 

Package fs
NPM Install Node.js built-in
Functions Check or manage local PC folder
Usage var fs                     = require(‘fs’);

 

//check if logFolder is existing. Otherwise, create this folder

fs.existsSync(logFolder) || fs.mkdirSync(logFolder);

 

Package file-stream-rotator
NPM Install npm install file-stream-rotator
Functions Define the log file properties like log4j, such as rotation period ‘daily‘ and log file name demo2_%DATE%.log’
Usage var FileStreamRotator    = require(‘file-stream-rotator’);

//Logger details

var logFileStream = FileStreamRotator.getStream({

date_format:   ‘YYYY-MM-DD’,

filename:           logFolder + ‘/demo2_%DATE%.log‘,

frequency:        ‘daily‘,

verbose:            false

});

 

Package morgan
NPM Install npm install morgan
Functions Streaming the logging message to log file
Usage var morgan         = require(‘morgan’);

 

//Assign the logger with file stream

app.use(morgan(‘combined’, {stream: logFileStream}));

 

Package mysql
NPM Install npm install mysql
Functions MySQL driver in order to connect to MySQL DB
Usage //Declare MySQL library

var mysql             = require(‘mysql’);

//Declare MySQL connection pool

var pool =  mysql.createPool({

host:                      ‘localhost’,

user:                      ‘root’,

password:           ‘root’,

database:            ‘itblogs2’,

port:                      3306

});

//Getting DB connection from connection pool, and then running SQL

exports.runQuery = function(query,callback) {

//Making Query

pool.getConnection(function(err, connection){

connection.query( query, function(err, rows){

if(err)    {

throw err;

}else{

console.log( query );

callback(rows);

}

});

connection.release();

});

};

 

Package http-status-codes
NPM Install npm install http-status-codes
Functions Provide the HTTP response status, such as:

200 – HttpStatus.OK

404 – HttpStatus.NOT_FOUND

409 – HttpStatus.CONFLICT

Usage var HttpStatus                                   = require(‘http-status-codes’);

//response the request with HTTP status 200 – HttpStatus.OK

res.send( HttpStatus.OK );

 

Package path
NPM Install Node.js built-in
Functions This package helps to manipulate the file path easily
Usage var path                                               = require(‘path’);

app.use(express.static( path.join(__dirname, ‘/public’)));

 

Package socket.io
NPM Install npm install socket.io
Functions Socket IO for server side
Usage // Define socket IO

var io                                     = require(‘socket.io’)();

//When new client is connected

io.on(‘connection’, function (socket) {

console.log(‘hello… you are connected (id=’ + socket.id + ‘).’);

_socket = socket;

 

//Receiving incoming message ‘message_reply’

socket.on(‘message_reply’, function(msg) {

console.info(‘message_reply : ‘+msg);

});

 

//When disconnect

socket.on(‘disconnect’, function() {

console.info(‘Socket id=’ + _socket.id + ‘ has gone.’);

});

});

 

Package socket.io-client
NPM Install npm install socket.io-client
Functions Socket IO for client side, sending socket message
Usage // Define client socket IO

var io                     = require(‘socket.io-client’);

var client              = io.connect(‘http://localhost:3000’);

//Receiving incoming message ‘ping_client’

client.on(‘ping_client’, function(msg) {

console.info(‘Receiving ping message from server : ‘+msg);

 

//Send message to server

client.emit(‘message_reply’, ‘Hi server, got your message’);

console.info(‘Sending ack message to server’);

});

 

Please rate this