Node.js: Built-in Modules


3 min read

OS Module

This module provides information about the operating system and computer specifications.

// Importing built-in os module
const os = require('os');
console.log(os.type());            // Tells base kernel of OS
console.log(os.version());        // Gives OS version
console.log(os.release());        // Tell OS release of base kernel
console.log(os.hostname());        // Tell main user name    
console.log(os.platform());        // Tells if wondows, linux, apple, etc.
console.log(os.userInfo());        // Gives user ID, name and other info
console.log(os.totalmem());        // Tells total RAM
console.log(os.freemem());        // Tells available RAM
console.log(os.uptime());        // Tells CPU uptime

Path Module

This module is useful for getting information about file paths. Let's see an example of a 'sep' property that gives a path separator character for a specific platform.

// Importign path module
const path = require("path");
// Output: /

The 'join()' method is used to generate a path if we know the folder and filename:

// Joins the folders and file using the platform specific separator
let myPath = path.join("parent", "child", "file.txt");
// Output: parent/child/file.txt

The'basename()' method gives the resulting file name if we already have the path:

// Gives the last final file name of a path

The 'resolve()' method can be used to generate an absolute path for a file:

// '__dirname' gives absolute path form home to current app and 
// Remaining folders are resolved together to get absolute path
console.log(path.resolve(__dirname, "parent", "child", "file.txt"));

FS Module

The file system module provides methods for file handling. There are two methods of file handling using this module:

  1. Synchronous Method

  2. Asynchronous Method

Synchronous Method:

In this method, file handling is done serially and in a blocking way. No other line of code is executed until and unless the file operation(open/read/write) is complete.

Let's see an example of reading a file synchronously.

// Importing file system module
const fs = require("fs");
// readFileSync(filePath, encodingMethod)
let data = fs.readFileSync("./myFile.txt", "utf8");

Now, file writing can be done as:

let message = "This is a text to be written."
// writeFileSync(filePath, Message, FlagObject)
fs.writeFileSync("./two.txt", message, {flag: "a"});

Here, the 'a' flag is optional and it indicates append mode. So, the content is appended from the end of the file every time we run this code.

Asynchronous Method:

This method is mostly preferred because file handling is done in a non-blocking way. Other lines of code can be executed while file operation is being performed in the background.

Let's see an example of reading a file asynchronously.

const fs = require("fs");
function handleRead(err, res)
    if(err) console.log(err);                    // Check for error
    else console.log(res);                        // Display response
// readFile(filePath, encodingMethod, callbackFunction)
fs.readFile("./one.txt", "utf8", handleRead);

In the asynchronous method, instead of assigning the file content to a variable, we need to provide a callback function to the 'readFile()' method which gives access to the file content. Similarly, we can perform the write operation as follows:

let message = "This is a text to be written."
function handleWrite(err, res)
    if(err) console.log(err);    // Check for error
    else console.log(res);        // We'll get no response on write
// writeFile(filePath, Message, FlagObject, Callback)
fs.writeFile("./two.txt", message, {flag: "a"}, handleWrite);

HTTP Module

This module allows us to create a server and listen to specified ports to serve the client. Let's see an example by creating a server and working with request and response.

// Importing http module
const http = require("http");
// Creatign a web server to process request and give response
const server = http.createServer((req, res) =>{
    // Print request method: GET, POST, DELETE, etc.
    // Write some message on browser 
    if(req.url=="/") res.write("You are in home page");
    else res.write("Oops. You are on the wrong page!");
    res.end("\nEnd of Response!");    
// Making the server to listen to port: 5000

To see the output of this app, we need to open 'localhost:5000' in our browser. The 'createServer()' takes a callback function which allows us to process the user request and give a response according to the request. The 'res.end()' method indicates that we won't respond further.