A simple beginner’s guide to Node.Js and Npm (Part 3)

Varad Shevade
5 min readAug 5, 2020

Most frequently needed inbuilt modules.

  • http/https: This module is used when you want to make and serve http requests. It is useful if you want to GET/POST/PUT data from a remote location, or if you want to build a server which serves these requests.

Remember to use require(“http”) to use this module.

Example: Creating a server with http

const http = require('http');
const requestListener = function (req, res) {
res.writeHead(200,{
'Content-Type': 'text/plain'
});
res.end('This is demo 1.');
}
const server = http.createServer(requestListener);
server.listen(3001);

Here http.createServer() returns a new instance of http.Server.

listen() is used to open the connection and listen to incoming requests on the port “3001” for the created server.

The createServer() will take a function as input. Here we have provided a function called requestListener. This function is automatically added to the request event, which has 2 parameters, request (for incoming message) & response (for server response).

The req is the request object, it contains data like header, body, params etc.

The res is the server response object, it contains properties like statusCode, statusMessage etc.. And functions like setHeader(), write(), end() etc. In the example we have sent a response code of “200” , with a response header of “Content-Type” , and a string message.

Example: Make a request with http.

const http = require('https');
const options = {
method: "GET",
hostname: "nodejs.org",
path: "/dist/index.json"
}
const request = http.request(options, (response) => {
var body = "";
response.setEncoding("utf8");
response.on("data", (chunk) => {
body = body+chunk; //appending chunked responses to form a single response body
});
response.on("end", () => {
console.log(JSON.parse(body));
});
});
request.end();

Here we have used http.request(), to make an api request to a remote location for data. Based on the request url, protocol can either be http/https. In our case we have used “https”.

Provided “options” for the request() are:

method: (eg. GET/POST/PATCH),

hostname: base url of the requested resource,

path: which will contain the endpoints, with url & query parameters as per url’s requirement.

Following events of “response” are used:

“data”: this event is emitted for consuming the response data. Data is returned in chunks, hence it must always be appended until no data in the response object exists.

“end”: this event is emitted when all the data from the response object is consumed.

Find more detailed info at:

https://nodejs.org/docs/latest-v13.x/api/http.html

https://nodejs.org/docs/latest-v13.x/api/https.html

  • path: This module provides utilities for working with the paths of files and directories. It produces different results on different OS. Use require(“path”) to import the module in your code.

Following are some of the frequently needed methods:

path.join([…paths]): Takes a string array of paths, and joins all of them.

Eg.: path.join(“/root”, “foo”, “bar”);output: /root/foo/bar

path.sep: platform specific path separator, Windows: “\”, POSIX: “/”

Eg.:

var loc = /foo/bar"
loc.split(path.sep);
output: [“foo”, “bar”]

path.extname(path): returns extension of the file in the given path.

Eg.: path.extname(“index.js”);output: .js

path.dirname(path): returns directory name of the given path.

Eg.: path.extname(“/foo/bar/index.js”);output: /foo/bar

Find more detailed info at https://nodejs.org/docs/latest-v13.x/api/path.html.

  • fs: Provides api for working and interacting with file systems. It has both synchronous and asynchronous forms of api.

Following are some of the frequently needed methods:

fs.access(path, mode, callback): Checks permission, as well as presence of the file in the file system. A callback is associated with a boolean value to ensure the availability.

Eg.:

const fs = require("fs");
// Check if the file exists in the current directory.
fs.access(file, fs.constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});

Following modes available: fs.constants.R_OK (read access), fs.constants.W_OK (write access). fs.accessSync() also available to do the same, but synchronously.

fs.createReadStream(path[, options]): Perhaps one of the widely used function. It opens up a readable stream of the given path.

Eg.:

const fs = require("fs");
fs.createReadStream("testfile.txt", {encoding: "utf8"})
.on('data', (data) => {
console.log(data);
}).on('close', () => console.log('Reading Done'));

Here ReadStream will be an event object that will emit following events.

i). “data”: This event is emitted when the stream contains data from the source.

ii). “close”: This event is emitted when the associated file descriptor(file) closes.

Other events also exist like: “open”, “ready”.

fs.createWriteStream(path[, options]): a stream that can write to a file. Optimal option for writing large data to a file.

Eg.:

const fs = require('fs');
var wstream = fs.createWriteStream(outputfile.txt');
wstream.write('This is demo 1.\n');
wstream.write('This is demo 2.\n');
wstream.end();Here the write method will push the data into the stream which is responsible for writing the data to the file.

fs.unlink(path): Removes the file from the given path. This method is asynchronous.

Eg.:

const fs = require('fs');
fs.unlink( './testfile.txt', (err) => {
if (err) { console.error(err);}
else { console.log("File Removed") }
});

A synchronous version also exists called fs.unlinkSync(path). This removes the file synchronously, thereby blocking the event loop.

Eg.: fs.unlinkSync( ‘./testfile.txt’);
  • Other methods of the “fs” module that are widely used are. readFile, readFileSync, writeFile, writeFileSync. These methods directly load the entire data of the file onto memory thereby creating instability when the size of the file is too large. Thus it is always a better option to stick to the “streams” as they deal with data in chunks.

Detailed info at: https://nodejs.org/api/fs.html

  • process: An object, with information and control of current node.js process. Being global in nature it does not require to be accessed with require().

Following are some of the frequently needed entities:

process.env: returns the “env” object, which contains the user environment variable. These variables can be set inside the node.js process, and will be inaccessible outside that node process. They can also be set in the OS user environment variable section, which can be then directly used inside the code.

Eg.: An environment variable object as follows:

“USER” : user@1

“SERVER” : server@1

“FOO”: “foo”

“BAR”: “bar”

Now a console.log(process.env.FOO) will output “foo”.

process.cwd(): Returns current working directory of the node.js process.

Eg.: console.log(process.cwd());

process.pid: PID of the process assigned by OS.

process.platform: return OS platform. Following platforms returned.: win32, linux, freebs, aix, darwin, openbsd, sunos.

process.exit(): Synchronously terminates the node.js process with exit status code. If status ‘0’ then exited with success.

Detailed info at:

https://nodejs.org/api/process.html

  • Cluster: Used to fully utilize the multi core processors. Best for handling load. Here use require(‘cluster’) to import the cluster module into your code. Through your master cluster, which can be identified with cluster.isMaster property, you can spawn multiple child clusters. These child clusters should match the number of cpu cores. Eg.:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
//inside worker cluster
console.log(`This is worker: ${process.pid}`);
}

Detailed info at: https://nodejs.org/docs/latest-v13.x/api/

Don’t forget to checkout part 4 of the tutorial at:

--

--