Node.js Built-in Modules

Node Built-in modules are easy to perform most common tasks that we need to use while developing an applicaton.

Introduction to Node.js Built-In Modules

  1. Node.js built-in modules are libraries of pre-written code that provide a wide range of functionalities.
  2. You can use them by importing the module using the require statement.
const fs = require('fs');

Node fs Module (File System)

  1. The fs module allows you to work with the file system. You can read, write, and manipulate files with it.
const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
    console.error(err);
    return;
    }
    console.log(data);
});
    

Node http Module

  1. The http module helps you create a web server in Node.js.
const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, Node.js!');
});

server.listen(3000, () => {
    console.log('Server is running on port 3000');
});
    

Node path Module

  1. The path module provides utilities for working with file and directory paths.
const path = require('path');

const filePath = path.join(__dirname, 'images', 'myImage.jpg');
console.log(filePath);
    

Node.js events Module

  1. The events module allows you to work with events and event emitters.
  2. You can create your own custom events or use predefined ones.
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

myEmitter.on('myEvent', () => {
    console.log('Event occurred!');
});

myEmitter.emit('myEvent');
    

Node OS Module

  1. The os module provides information about the operating system.
  2. You can get details like the CPU architecture, free memory, and more
const os = require('os');

console.log('CPU Architecture:', os.arch());
console.log('Free Memory:', os.freemem());
console.log('Total Memory:', os.totalmem());
    

Node Custom Modules

  1. A custom module in Node.js is simply a separate JavaScript file that contains functions, objects, or values that you want to reuse in other parts of your application.
  2. Custom modules help you keep your code organized and make it easier to maintain.

How to Create a Custom Module

  1. To create a simple custom module in Node. Start by creating a new JavaScript file (e.g., myModule.js) and add the following code to it
// myModule.js
const greet = () => {
    return "Hello, Node.js!";
};

module.exports = greet;
    

In this example, we've defined a function called greet and exported it using module.exports. This makes the greet function available for use in other parts of your application.

Using a Custom Module

  1. Now, let's use the custom module we created in another JavaScript file.
  2. Create a new file (e.g., app.js) and use the require function to import the module
// app.js
const customGreet = require('./myModule');
console.log(customGreet());
    

In this example, we import the myModule.js module using require, and we can use the customGreet function in our app.js file. When you run app.js, it will output:

Hello, Node.js!

Exporting Multiple Functions and Values

  1. You can export multiple functions, objects, or values from a custom module.
  2. Let's extend our myModule.js to export two functions
// myModule.js
    const greet = () => {
      return "Hello, Node.js!";
    };
    
    const farewell = () => {
      return "Goodbye, Node.js!";
    };
    
    module.exports = {
      greet,
      farewell,
    };
    

Now, in your app.js, you can use both functions

// app.js
const customModule = require('./myModule');
console.log(customModule.greet());
console.log(customModule.farewell());

When you run app.js, it will output

Hello, Node.js!
Goodbye, Node.js!