Tuesday 14 November 2017

Node.js | Node.js Web Server

We need the web server to access web pages of any web application. The web server will handle all the http requests for the web application.
IIS is a web server for ASP.NET web applications and Apache is a web server for PHP or Java web applications.

Node.js has capabilities to create own web server which will handle HTTP requests asynchronously. We can use IIS or Apache to run Node.js web application as well but it is recommended to use Node.js web server.

Create Node.js Web Server
Node.js makes it easy to create a simple web server that processes incoming requests asynchronously.

NodeServer.js
<!-- Step. 1: Import Node.js core module -->
var http = require('http');
var server = http.createServer(function (req, res) {
<!-- Step. 2: Handles incoming requests here -->
 
});
<!-- Step. 3: Listen for any incoming requests -->
server.listen(8080);
 
console.log('Node.js web server is running on port 8080..');

Step.1: Import Node.js core module
We import the http module using require() function. The http module is a core module of Node.js, so no need to install it using NPM.

Step.2: Handles incoming requests here
The next step is to call createServer() method of http and specify callback function with request and response parameter.

Step.3: Listen for any incoming requests
Finally, call listen() method of server object which was returned from createServer() method with port number, to start listening to incoming requests on port 8080. We can specify any unused port here.

Output:
D:\node>node NodeServer.js
Node.js web server is running on port 8080..

Handle HTTP Request:
The http.createServer() method includes request and response parameters which is supplied by Node.js. The request object can be used to get information about the current HTTP request e.g. URL, request header and the data. The response object can be used to send a response for a current HTTP request.

HandleHttpReqRes.js
<!-- Import Node.js core module -->
var http = require('http');
<!-- create web server -->
var server = http.createServer(function (req, res) {
    <!-- Check the URL of the current request -->
    if (req.url == '/') {
        // set response header
        res.writeHead(200, { 'Content-Type': 'text/html' });
       
        // set response content   
        res.write('<html><body><p>Home Page</p></body></html>');
                console.log('http://localhost:8080: Home Page..')
        res.end();
   
    } else if (req.url == "/admin") {
        res.writeHead(200, { 'Content-Type': 'text/html' });
                console.log('http://localhost:8080/admin: Admin Page..')
        res.write('<html><body><p>Admin Page</p></body></html>');
        res.end();
    } else {
        res.end('Invalid Request!');
        }
});
<!-- listen for any incoming requests -->
server.listen(8080);

console.log('Node.js web server at port 8080 is running..');

In the above example, req.url is used to check the URL of the current request and based on that it sends the processed response. To send a response, first it sets the response header using writeHead() method and then writes a string as a response body using write() method.

Finally, Node.js web server sends the response using end() method.

D:\node>node HandleHttpReqRes.js
Node.js web server at port 8080 is running..
http://localhost:8080: Home Page..
http://localhost:8080/admin: Admin Page..

Sending JSON Response
The following example demonstrates how to serve JSON response from the Node.js web server.
HttpJSONRes.js
var http = require('http'); 
var server = http.createServer(function (request, response) {   
    <!-- Check whether the URL is currect or not. -->
    if (request.url == '/data') {
         response.writeHead(200, { 'Content-Type': 'application/json' });
         response.write(JSON.stringify({ message: "Hello World"}));  
         response.end();  
    }
});
server.listen(8080);
console.log('Node.js web server at port 8080 is running..');

Output
D:\node>node HttpJSONRes.js
Node.js web server at port 8080 is running..

{"message":"Hello World"}



Monday 13 November 2017

Node.js | Node Package Manager

Node Package Manager (NPM) is a command line tool that installs updates or uninstalls Node.js packages in the application. It is an online repository for open-source Node.js packages. The node community around the world creates useful modules and publishes them as packages in this repository.

NPM provides two main functionalities:
1. It provides online repositories for node.js packages/modules which are searchable on search.nodejs.org.
2. It also provides command line utility to install Node.js packages, do version management and dependency management of Node.js packages.

It has now become a popular package manager for other open-source JavaScript frameworks like AngularJS, jQuery, Gulp, Bower etc.

NPM is included with Node.js installation. After installing Node.js, we can verify NPM installation by using the following command on the terminal or command prompt.

C:\>npm -v
5.5.1

C:\>npm version
{ npm: '5.5.1',
ares: '1.10.1-DEV',
cldr: '31.0.1',
http_parser: '2.7.0'
icu: '59.1',
modules: '57',
node: '8.1.2',
openssl: '1.0.2l',
tz: '2017b',
unicode: '9.0',
uv: '1.12.0',
v8: '5.8.283.41',
zlib: '1.2.11' }

If we have an older version of NPM then it can be updated it to the latest version using "npm install npm –g" command.
C:\>npm install npm -g
C:\Users\awadh\AppData\Roaming\npm\npx -> C:\Users\awadh\AppData\Roaming\npm\node_modules\npm\bin\npx-cli.js
C:\Users\awadh\AppData\Roaming\npm\npm -> C:\Users\awadh\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js
+ npm@5.5.1
added 460 packages in 158.314s

To access NPM help, write "npm help" in the command prompt or terminal window.
C:\>npm help

Usage: npm <command>

where <command> is one of:
access, adduser, bin, bugs, c, cache, completion, config,
ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
explore, get, help, help-search, i, init, install,
install-test, it, link, list, ln, login, logout, ls,
outdated, owner, pack, ping, prefix, profile, prune,
publish, rb, rebuild, repo, restart, root, run, run-script,
s, se, search, set, shrinkwrap, star, stars, start, stop, t
team, test, token, tst, un, uninstall, unpublish, unstar,
up, update, v, version, view, whoami

npm <command> -h     quick help on <command>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
C:\Users\awadh\.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

npm@5.5.1 C:\Users\awadh\AppData\Roaming\npm\node_modules\npm

NPM performs the operation in two modes:
1. Global and
2. Local.

In the global mode, NPM performs operations which affect all the Node.js applications on the computer whereas, in the local mode, NPM performs operations for the particular local directory which affects an application in that directory only.

Install the package Locally:
Below given command can be used to install any third party module in the local Node.js project folder.
C:\>npm install <package name>

For example, the following command will install ExpressJS into node folder of D drive.
D:\node>npm install express
npm WARN saveError ENOENT: no such file or directory, open 'D:\node\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'D:\node\package.json'
npm WARN node No description
npm WARN node No repository field.
npm WARN node No README data
npm WARN node No license field.

+ express@4.16.2
added 48 packages in 18.12s


All the modules installed using NPM are installed in node_modules folder.

Add Dependency into package.json:
Command "npm install <module_name> –save" can be used to add dependency entry into package.json of the application.

For example, "npm install express –save" will install ExpressJS in the application and adds dependency entry into the package.json as well.
D:\node>npm install express --save
npm WARN saveError ENOENT: no such file or directory, open 'D:\node\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'D:\node\package.json'
npm WARN node No description
npm WARN node No repository field.
npm WARN node No README data
npm WARN node No license field.

+ express@4.16.2
updated 1 package in 4.222s

The package.json of the project will look something like below.
package.json
{
"requires": true,
"lockfileVersion": 1,
"dependencies": {
"express": {
"version": "4.16.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.16.2.tgz",
"integrity": "sha1-41xt/i1kt9ygpc1PIXgb4ymeB2w=",
"requires": {
"accepts": "1.3.4",
"array-flatten": "1.1.1",
"body-parser": "1.18.2",
"content-disposition": "0.5.2",
"content-type": "1.0.4",
"cookie": "0.3.1",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "1.1.1",
"encodeurl": "1.0.1",
"escape-html": "1.0.3",
"etag": "1.8.1",
"finalhandler": "1.1.0",
"fresh": "0.5.2",
"merge-descriptors": "1.0.1",
"methods": "1.1.2",
"on-finished": "2.3.0",
"parseurl": "1.3.2",
"path-to-regexp": "0.1.7",
"proxy-addr": "2.0.2",
"qs": "6.5.1",
"range-parser": "1.2.0",
"safe-buffer": "5.1.1",
"send": "0.16.1",
"serve-static": "1.13.1",
"setprototypeof": "1.1.0",
"statuses": "1.3.1",
"type-is": "1.6.15",
"utils-merge": "1.0.1",
"vary": "1.1.2"
}
}
}
}

Install Package Globally:
NPM can also install packages globally so that all the node.js application on that machine can import and use the installed packages.

NPM installs global packages into "/<User>/local/lib/node_modules" folder. Apply -g in the install command to install the package globally.

Command to install ExpressJS globally is given below:
D:\node>npm install -g express
+ express@4.16.2
added 48 packages in 16.748s

Update Package:
To update the package installed locally in the Node.js project, we can run the following command on command prompt or terminal window on the project folder.
D:\node> npm update <package name>

Updating the ExpressJS using the following command:
D:\node>npm update express

Searching a Module:
"npm search express" command is used to search express or module.D:\node>npm search express

NAME                      | DESCRIPTION          | AUTHOR          | DATE       | VERSION  | KEYWORDS
express                   | Fast,…               | =hacksparrow…   | 2017-10-10 | 4.16.2   | express framework sinatra web rest restful
path-to-regexp            | Express style path…  | =defunctzombie… | 2017-10-20 | 2.1.0    | express regexp route routing
morgan                    | HTTP request logger… | =dougwilson     | 2017-09-27 | 1.9.0    | express http logger middleware
express-session           | Simple session…      | =defunctzombie… | 2017-09-26 | 1.15.6   |

Uninstall Packages:
Use the following command to remove a local package from the project.
D:\>npm uninstall <package name>

The following command will uninstall ExpressJS from the application.
D:\node>npm uninstall express
npm WARN saveError ENOENT: no such file or directory, open 'D:\node\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'D:\node\package.json'
npm WARN node No description
npm WARN node No repository field.
npm WARN node No README data
npm WARN node No license field.

removed 1 package in 2.005s
Related Posts Plugin for WordPress, Blogger...