Tuesday, March 31, 2020

Node.js URL Module

Node.js URL Module


The Node.js URL Module is provided to perform operations with address URLs. We can split a web address into manageable parts. A URL string may carry information including the protocol such as https, the hostname, query string values and more.

This is a built-in module, so no need to install this module exclusively. It can be included using the require() method.

var url = require('url');

URL Strings and URL Objects


A URL string is a structured string composed of several meaningful components. We can parse a URL string to get the URL object possessing properties for each of these components.

We can parse an address with the url.parse() method, and it will return a URL object with each part of the address as properties:

            var url = require('url');
      var adr = 'http://localhost:3000/index.html?year=2020&month=March';
      var u = url.parse(adr, true);
      console.log(u.host);
      console.log(u.pathname);
      console.log(u.search);
      var qdata = u.query;
      console.log(qdata.month);
      /* Output must be,

      localhost:3000
      /index.html
      ?year=2020&month=March
      March
      */


Node.js url.format() method


We can create a URL from an object using the format() method. The object must contain the protocol hostname and the path property. This object may also contain other properties like hash links and query strings.


             const url = require('url');
      const page = url.format({
              protocol: 'https',
              hostname: 'www.programminghunk.com',
              pathname: 'p/nodejs.html',
              hash: 'Overview'
          });
      console.log(page);
      /*
https://www.programminghunk.com/p/nodejs.html#Overview
      */

The URL constructor


The URL constructor creates a new URL object by parsing the input relative to the base. If the base is passed as a string, it will be parsed equivalent to new URL(base). We can visualize components of a URL as,

URL Components
URL Components
The components of the URL can be accessed as the properties of the URL object. All the properties of a URL object can be listed as,

  • url_obj.auth
  • url_obj.hash
  • url_obj.host
  • url_obj.hostname
  • url_obj.href
  • url_obj.path
  • url_obj.pathname
  • url_obj.port
  • url_obj.protocol
  • url_obj.query
  • url_obj.search
  • url_obj.slashes


           let url = require('url');
      // Constructor
      let mypage = new URL('http://pushpendra:1234@localhost:3000/Node/tutorials?k=first#intro');
      
      console.log("origin "+mypage.origin);
      console.log("protocol "+mypage.protocol);
      console.log("username "+mypage.username);
      console.log("password "+mypage.password);
      console.log("Host "+mypage.host);
      console.log("hostname "+mypage.hostname);
      console.log("Port "+mypage.port);
      console.log("pathname "+mypage.pathname);
      console.log("search "+mypage.search);
      console.log("hash "+mypage.hash);
      console.log("href "+mypage.href);
      console.log("toString"+mypage.toString());
      /*
      origin http://localhost:3000
      protocol http:
      username pushpendra
      password 1234
      Host localhost:3000
      hostname localhost
      Port 3000
      pathname /Node/tutorials
      search ?k=first
      hash #intro
      href http://pushpendra:1234@localhost:3000/Node/tutorials?k=first#intro
      toStringhttp://pushpendra:1234@localhost:3000/Node/tutorials?k=first#intro
      */


Monday, March 30, 2020

Node.js fs Module

The fs module


We can perform the file operations with Node.js on our computer. The fs module provides all the essential functionalities to access and interact with the file system. This is a built-in module, so it is a component of core Node.js. We do not need to install it separately, just use require() method to include this module into your application.

const fs = require('fs');

All of the general operations to access and manipulate file can be performed with the File System module,

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files
There are several methods provided by fs module, Few important methods are listed here,

Method Description
fs.access() test if the file exists and Node.js can access it with its permissions
fs.readFile() read the data in a file
fs.appendFile() append content to a file. If the file does not exist, it will be created
fs.chmod() update the permissions of a file specified by the filename passed.
fs.copyFile() copies content of a file
fs.mkdir() create a new folder
fs.open() set the file mode
fs.close() close a file descriptor
fs.rename() rename a file or folder
fs.writeFile() write content in the file
fs.unlink()  remove a file or a symbolic link
fs.rmdir()  remove a folder

Read Files


To read the content from a file, we can use fs.readFile() function.

Let's create an HTML file and place it in your project folder, Let the name of the file be index.html,

<html>
   <head>
      <title>Test File</title>
   </head>
   <body>
       This is an example.
       The server is runing fine!
   </body>
</html>


Now, Create a file as files.js in the same folder to read the HTML(index.html) file, and return the content in this file.

var http = require('http');
      var fs = require('fs');
      http.createServer(function (request, response) {
        fs.readFile('index.html', function(err, data) {
          response.writeHead(200, {'Content-Type': 'text/html'});
          response.write(data);
          response.end();
        });
      }).listen(3000);
      console.log('Serving at http://localhost:3000');

Initiate files.js,

C:\Users\usr\project_name> node files.js

If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:3000

The result will be seen as,


Create Files

We can write content to file using appendFile(), open() or writeFile() method.

In the example below, appendFile() method is used to append the content to the file. A new File is created if it does not exist, 


      var fs = require('fs');
      fs.appendFile('welcome.txt', 'welcome to Node.js', function (err) {
        if (err) throw err;
        console.log('Saved!');
      });

      console.log('File appended successfully');


The writeFile() method replaces the file and content if it exists. Otherwise, a new file is created if does not exist, and the input content will be placed in this file.


      var fs = require('fs');
      fs.writeFile('welcome.txt', 'welcome to Node.js(content will be overwritten)', function (err) {
        if (err) throw err;
        console.log('Content Saved!');
      });


      console.log('File is overwritten successfully');


Delete Files


We can use unlink() method to remove a file or a symbolic link. To remove a folder rmdir() method can be used.

To delete a file with the File System module, use the fs.unlink() method.

For example to delete welcome.txt

   var fs = require('fs');
      fs.unlink('welcome.txt', function (err) {
        if (err) throw err;
        console.log('file deleted successfully');

      });



Rename A File

A file can be renames with fs module using the rename() method.
For example
To rename "welcome.txt" to “myfile.txt",

   var fs = require('fs');
      fs.rename('welcome.txt', 'myfile.txt', function (err) {
        if (err) throw err;
        console.log('File Renamed successfully');

      });


Sunday, March 29, 2020

Node.js HTTP Module

Node.js HTTP Module


The HTTP Module in Node.js


Node.js offers http module to enable the applications with HTTP transmission, and it is one of the most important modules available in Node.js. This is a built-in module that allows Node.js applications to transfer data over the network using the HyperText Transfer Protocol (HTTP).

We can use the require() method to include this module,

var http = require('http');

Node.js as a Web Server


We can create an HTTP server that listens to server ports for any client requests and send a response back to the client. Node.js provides http module with a createServer method. This method returns an object that we can use to respond to HTTP requests over the network. This object inherits the http.Server prototype.

The Architecture of a web application


The architecture of typical web application can have client, web server, business service layer and data layer as its components,

Web Application architecture
Web Application architecture



Adding HTTP Header


We can create a web server in Node.js with HTTP Module, for this we can use createServer() method. We can add the HTTP header with content-type information in this method.

const http = require('http');
        http.createServer(function (request, response) {
          response.writeHead(200, {'Content-Type''text/html'});
          response.write("<h3>Welcome to the response page...</h3>");
          response.end();
        }).listen(3000);

        console.log('Server running at http://127.0.0.1:3000/');


The first argument of the response.writeHead() method represents the status code, 200 means that, the response status is OK, and a second argument is an object providing HTTP content-type information to the response headers.

Read the Query(Request) String


The http.createServer() function has first argument as request argument. This argument contains the request object from the client (http.IncomingMessage object). This object holds url property received from the client appended to the domain name.

 const http = require('http');
        http.createServer(function (request, response) {
          response.writeHead(200, {'Content-Type': 'text/html'});
          response.write("URL: "+request.url);//url
          response.end();
        }).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');


Enter the http://localhost:3000/HomePage in your browser, you can see,


URL: /HomePage


as a result,

Parsing the Query String


We can parse the request string and retrieve the request parameters easily, for example

        const http = require('http');
        const url = require('url');

        http.createServer(function (req, res) {
          res.writeHead(200, {'Content-Type': 'text/html'});
          const q = url.parse(req.url, true).query;
          const txt = parseInt(q.num1) + parseInt(q.num2);
          res.end("sum is "+txt);

        }).listen(3000);


Enter the http://localhost:3000/?num1=100&num2=50 in your browser, you can see,

sum is 150

as a result

Node.js Modules

Node.js Modules

What is a Module?


A module in JavaScript can be visualized something like JavaScript libraries. A module is a set of functions that we may need to include in our application.

A module can be considered as a set of simple or complex functionality that can be contained in a single or multiple JavaScript files. A module can be reused inside the entire Node application.

Each module has its own context, so it should not interfere with other modules or disturb the global scope. All of the modules can be kept in a separate .js file under a separate folder.

We can categorize Node.js modules as,

  • Built-in Modules
  • Local Modules
  • Third-party Modules


Built-in Modules

There are several built-in modules available by Node.js that do not require any additional installation before use. Node.js is a lightweight framework. These built-in modules are the core modules and include bare minimum functionalities to enable Node.js. These core modules are compiled into its binary distribution and load automatically when the Node.js process starts. We still need to import the core module to make use of their functionality in our application. http, url, fs, querystring, path, util are the example of Built-in Modules.

How to add include Modules?

We can use the require() function along with the name of the module as an argument to include a module in a script.

For example

const http=require(‘http’); 

Now we can use the included module.

var http = require('http');
        http.createServer(function (request, response) {
          response.writeHead(200, {'Content-Type': 'text/html'});
          response.end('Hello World!');
        }).listen(8087);

Local Modules

The modules created locally in our Node.js application are called local modules.

Constructing our own Modules

We can construct our own modules (Local modules) to include and use them in our applications. Let’s create a module that simply returns a date and time object,

exports.myDateTime = function () {
             return Date();

};

The exports keyword is used to make properties and method defined in our module available outside the module file.
Save the script written above in a file as "my_module.js"


Example to include a Module


        const http = require('http');
        const date = require('./my_module');

        http.createServer(function (request, response) {
          response.writeHead(200, {'Content-Type': 'text/html'});
     response.write("<h3>Date and Tmie: " + date.myDateTime()+" </h3>");
          response.end();
        }).listen(8087);



We must use ./ to locate the module, it indicates that the module is available in the same directory as the Node.js document. 

Save the script in a file as "test_module.js", and execute the script: 


Start demo_module.js: 



C:\Users\user> node test_module.js 


If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8087

The result will be shown as,

result