Node Basic

Node has a number of built-in modules, ranging from filesystem access in a module called fs to utility functions in a built-in module called util.

A common task when building web applications with Node is parsing the URL.
When a browser sends a request to your server, it will ask for a specific URL, such as the home page or the about page. These URLs come in as strings, but we’ll often want to parse them to get more information about them. Node has a built-in URL parser module; let’s use it to see how to require packages.

var url = require("url");
var parsedURL = url.parse("
➥ profile?name=barry");
console.log(parsedURL.protocol); // "http:"
console.log(; // ""
console.log(parsedURL.query);  // "name=barry"

Here in this example, we have to include URL module of Node.  Node has several built-in modules, but some it may not be enough, so we have to use third party module.  If we want to use the third party package then we have to define it in the package.json as a dependency.

Syntax for install third party package as npm
npm install thirdPartyPackageName –save.

Syntax for creating new project
npm init

Upgrading node to latest stable in ubuntu:

/** used sudo if you not fixed perssion for node */
>>npm cache clean -f
>>npm install -g n
>>n stable

/** If n stable show Permission error as below */
n stable
  installing : node-v12.14.1
       mkdir : /usr/local/n/versions/node/12.14.1
mkdir: cannot create directory ‘/usr/local/n’: Permission denied

/** need to add user perssion on local folder, run below code and 
replace with userName with your pc name */

>>sudo chown -R userName:userName /usr/local
>>n stable

/** If still showing old version, replace old version path to new version */
>>node -v

Creating our own node module

Step 1: For creating our own custom module we are creating a function that will generate the random number between 0 to 100 and name this function as random-integer.js

var MAX = 100;
function randomInteger() {
return Math.floor((Math.random() * MAX));
module.exports = randomInteger;  // Export the module for other file

NOTE:  module.exports can be anything you want. Anything to which
you can assign a variable can be assigned to module.exports. It’s a function
in this example, but it’s often an object. It could even be a string or a number
or an array if you’d like.

Step2: To use the randomInteger function in another file, we have to import our randomInteger() module first, before we can use in another file.

var randomInt = require("./random-integer");
console.log(randomInt()); // 12
console.log(randomInt()); // 77
console.log(randomInt()); // 8

Node Asynchronous World

Node is asynchronous in nature, If we had requested for the large external file to load from hard disk to server, which is external resources and when the second request comes to the Node. We don’t have to wait for the first request to finished. We can start our second request. The example here for reading a file from disk, while reading for the external file we can proceed with the next code, as Node asynchronous nature.

var fs = require("fs");
var options = { encoding: "utf-8" };
fs.readFile("myfile.txt", options, function(err, data) {
	if (err) {
		console.error("Error reading file!");
	console.log(data.match(/x/gi).length + " letter X's");

Callback Function:

Nodejs Asynchronous programming is a design pattern which ensures the non-blocking code execution. The callback function, promise and observable are frequently used in node asynchronous programming. Example 1:

const geoCapital = (address, callback) => {
	setTimeout(() => {
		const data = {
		    country: 'India',
			continent: 'Asia'
        console.log('Before Callback Function');
         }, 2000 )

geoCapital('Delhi', (data) => {
    console.log('Inside callback');
    console.log('end of callback');

The output of code >> node app.js

Before Callback Function
Inside callback
{ country: ‘India’, continent: ‘Asia’ }
end of callback

Example 2 of the callback function

const add = (a, b, callback) => {
	setTimeout(() => {
		callback(a + b)
         }, 2000 )

add(1, 4, (total) => {

Building Node web server in Node

The HTTP module that makes it possible to develop web servers with Node, and it’s what Express is built on.The http.create-Server function, this function takes a callback that’s called every time a request comes into your server, and it returns a server object. The following listing contains a very simple server that sends “Hello world” with every request.

var http = require("http");
function requestHandler(request, response) {
console.log("In comes a request to: " + request.url);
response.end("Hello, world!");
var server = http.createServer(requestHandler);  //Creates a server that uses your function to Starts the server handle requests

We can easily parse the request URL and we will show for dummy as

function requestHandler(req, res) {
if (req.url === "/") {
    res.end("Welcome to the homepage!");
} else if (req.url === "/about") {
    res.end("Welcome to the about page!");
} else {
    res.end("Error! File not found.");
Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top