Introduction to Node.js

Exploring Node.js Modules

A module system allows us to split and include code and import code written by other developers whenever required.

Eric Raymond proposed the Rule of Modularity: “Developers should build a program out of simple parts connected by well-defined interfaces, so problems are local, and parts of the program can be replaced in future versions to support new features. This rule aims to save time on debugging complex code that is complex, long, and unreadable.”

One of the main problems with building scalable systems with JavaScript is the lack of modularity or a standard interface for assembling a coherent program from many smaller ones. For instance, a typical web application might load dependencies using a sequence of <script> tags in the <head> section of an HTML document:

<head>
<script src="fileA.js"></script>
<script src="fileB.js"></script>
</head>

One problem with this approach is the lack of dynamic inclusion, which requires complicated hacks. If possible, all potential dependencies must be declared before being used. The introduced scripts are not encapsulated, fileB cannot address fileA, and there are diminishing opportunities for collaboration and reusability.

To solve these problems, Node.js is designed around Modules System, which allows developers to split codes into different files to maintain, organize and reuse code whenever possible.

A module is nothing but a JavaScript file. Node.js has many built-in modules that are part of the platform and come with Node.js installation, for example, HTTP, fs, path, and more.

A Node module uses two formats — CommonJS and ESM(EcmaScript). You can get a detailed comparison of CommonJS and ESM, but a simple difference lies with how developers can import and export each module.

CommonJS uses the require method for importing modules and module.exports to export and expose modules, while ESM uses import to import modules and export to export and expose modules.

Popular Built-in Node.js Modules

Here are five popular built-in Node.js Modules and how to use them in your Node.js project.

  1. HTTP

  2. Fs

  3. Path

  4. Process

  5. URL

Node HTTP Module

The http module is used to create an HTTP server in Node.js. It is one of the most popular Node.js modules because almost every web application built with Node.js uses it.

Here’s a simple example of using http module to build a simple web server in Node.js:

const http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('Welcome to this page!');
    res.end();
}).listen(3000);

In the code snippet above, I’m using the commonJS require syntax to import the http module from Node.js.

Next, I call the createServer function from the module to create a web server. After creating the server, it will call the callback function with the response( res ) and request( req ).

Next, I use the res property to specify what the server should return when it is called using the write, writeHead methods.

Lastly, I call the listen function and pass the port number I want the server to listen to. If you run this program using the following command:

node server.js

If everything is successful, visit [localhost:3000](<http://localhost:3000>) in your browser, and you should be greeted with Welcome to this page! on your browser.

Node FS Module

The fs is the acronym for File System. It’s used to handle file systems in Node.js. This module has many different methods to handle files in Node.js, using an asynchronous or synchronous approach.

Here’s a sample script to read the content of a file in Node.js:

/**
 * Node FS Read File
 * Node JS Read File
 */

var fs = require("fs");

fs.readFile('test.txt', 'utf8', function(err, data) {
	if(err) return
	console.log(data);
});

In the above code snippet, we use the readFile function from the fs module to read the content of the test.txt file.

The Path Module

The path includes methods to deal with file paths. Node.js made working with file and directory paths for Windows, Linux, or Mac operating systems easy.

Here’s a simple code snippet for accessing a specific file in a directory. Assuming we want to list all the files in the Documents folder in our system:

//requiring path and fs modules
const path = require('path');
const fs = require('fs');

//joining path of directory 
const directoryPath = path.join(__dirname, 'Documents');

//passsing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 

    //listing all files using forEach
    files.forEach(function (file) {
        // Do whatever you want to do with the file
        console.log(file); 
    });
});

In the code snippet above, we required both the fs and path modules since both will be useful. Next, we use the path.join function from the path module to join the current directory where we save this JavaScript file we are working with using the global __dirname with the Documents folder.

Next, we use the readdir function from the fs module to read the directory content we passed as the parameter. In our case, it's the Documents folder.

Lastly, we loop through all the files and log them to the console using JavaScript forEach.

The Process Module

The process module provides information and controls about the current Node.js process. With the process module, you can control the current Node process.

One of the most popular uses of the process module is to return an object containing the user environment.

Here’s a sample code snippet to return your application environment variable:

process.env.NODE_ENV
process.env.API_KEY

In the script above, we use the env property of the process module to return the NODE_ENV and API_KEY defined in our .env file.

The URL Module

The url module provides utilities for URL resolution and parsing. If you need to parse your URL, generate an acceptable URL format, or split your URL into a readable part in Node.js, the url module is your goto module.

Here’s how to split a URL into a readable part in Node.js:

var url = require('url');
var adr = '<http://localhost:3000/default.htm?year=2017&month=february>';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:3000'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'

First, we require the url module and parse our URL using the parse method from the url module. Now that the URL is parsed, we can work with different parts of the URL, as shown in the code snippet above.

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board