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

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

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.

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.

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

Eg.:

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

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

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.:

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.:

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.:

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

Eg.:

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

  • 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.

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.:

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

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

--

--

An enthusiastic engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store