Node.js Modules in Depth with Examples

node.js modules

This guide shows Node.js modules, how they work, how to import and export them, and why you use them.

What are Node.js Modules?

A module in Node.js holds code in one file. It hides that code from other files. You can load it and use its code inside another file.

Here is an example:

// math.js
function add(a, b) { return a + b; }
module.exports = add;

// index.js
const add = require('./math');
console.log(add(2, 3));

This code saves one function in math.js and then loads it in index.js to use it.

You can use modules to break code into parts. That helps code stay simple, and you can reuse it in other parts of the app.

How to Import and Export Modules in Node.js

You export a value or function from one file. You import that value into another file with require.

Here is an example:

// greet.js
module.exports = function(name) {
  return 'Hello ' + name;
};

// app.js
const greet = require('./greet');
console.log(greet('Ali'));

This code makes the greet function and exports it. Then it loads it in app.js and runs it.

Here is another example:

// user.js
exports.name = 'Sara';
exports.age = 22;

// app.js
const user = require('./user');
console.log(user.name + ' ' + user.age);

This code exports two values from user.js and then imports them in app.js.

Types of Node.js Modules (Core, Local, Third-party)

Node.js has three types of modules. Core modules come with Node.js. Local modules are files you create. Third-party modules come from npm.

Core Example:

const fs = require('fs');
fs.writeFileSync('note.txt', 'Hello');

This code uses the core fs module to write a file.

Local Example:

// data.js
module.exports = { city: 'Riyadh' };

// main.js
const data = require('./data');
console.log(data.city);

This code exports one value from data.js and loads it in main.js.

Third-party Example:

const _ = require('lodash');
console.log(_.upperCase('hello world'));

This code loads lodash from npm and uses it to change a string to upper-case words.

Use Built-In Core Modules (fs, http, path, etc.)

fs module:

const fs = require('fs');
fs.appendFileSync('log.txt', 'new line\n');

This code adds a line to a file named log.txt.

http module:

const http = require('http');
const server = http.createServer((req, res) => {
  res.end('Hi');
});
server.listen(3000);

This code creates a web server on port 3000.

path module:

const path = require('path');
console.log(path.join(__dirname, 'file.txt'));

This code makes a full path to a file.

Create a Custom Module in Node.js

You make your own module by writing code in one file and exporting it. You then load that file in another part of the app.

Here is an example:

// calc.js
exports.add = (a, b) => a + b;
exports.sub = (a, b) => a - b;

// index.js
const calc = require('./calc');
console.log(calc.add(5, 3));

This code creates a custom module, calc.js, with two functions. It loads that module in index.js to use its functions.

To work with NPM Packages as Modules:

You need to install a package with this command:

npm install package-name

Then you load it in your code with require. It acts like any other module.

Examples of Node.js Modules

Read JSON file with fs module:

const fs = require('fs');
const data = JSON.parse(fs.readFileSync('data.json'));
console.log(data);

This code loads a JSON file and shows its data on the console. It reads the file in sync and parses it to an object.

Build a small server with http module:

const http = require('http');
const server = http.createServer((req, res) => {
  res.write('Welcome');
  res.end();
});
server.listen(4000);

This code starts a server on port 4000 and sends text to any client that connects.

Use axios to call an API:

const axios = require('axios');
axios.get('https://api.github.com/users/octocat')
  .then(res => console.log(res.data));

This code uses axios from npm to fetch user data from GitHub API and prints it.

Wrapping Up

You learned what Node.js modules are and how you import and export them. You also saw built-in modules, custom modules, npm packages, and several examples.

Here is a quick recap:

  • The modules split code into parts and allow you to load them with require.
  • The core modules come with Node.js
  • Local modules are your own files
  • The third-party modules come from npm.

FAQs


What are Node.js Modules and why are they important?

Node.js Modules are reusable blocks of code that help organize applications.
  • Core modules: Built into Node.js (e.g., fs, http).
  • Local modules: Created by developers.
  • Third-party modules: Installed via npm.
They improve code reusability and project structure.

How to create and use a custom module in Node.js?

To create a custom module:

// math.js  
function add(a, b) {  
   return a + b;  
}  

module.exports = add;  
To use it in another file:

// app.js  
const add = require('./math');  
console.log(add(5, 3)); // Output: 8  

What are some commonly used built-in Node.js modules?

Most popular Node.js core modules:
  1. fs - File system operations
  2. http - Create servers
  3. path - Handle file paths
  4. os - Operating system info
  5. events - Event handling
Example:

const fs = require('fs');  
fs.writeFileSync('test.txt', 'Hello Node.js Modules!');  

How to install and use third-party modules in Node.js?

Use npm to install third-party modules.

// Install express  
npm install express  
Using express:

const express = require('express');  
const app = express();  

app.get('/', (req, res) => {  
   res.send('Hello from Express Module!');  
});  

app.listen(3000, () => console.log('Server running on 3000'));  

Similar Reads

Node JS Events in Depth with Examples

Node JS runs code in an event-based model and uses events to drive tasks. An event is a signal that…

Installing Node js on Windows, Ubuntu, and MacOS

Installing node js on Windows, Ubuntu, or macOS. You need to pick the version of Node.js that you want to…

Node.js HTTP Server with Examples for Beginners

This article shows how Node.js creates HTTP servers. It covers requests, responses, routes, HTML, JSON, and gives examples for both…

Node.js File System with Examples

Node.js file system lets you read, write, update, and manage files and folders with built-in methods. Understand the Node.js File…

Node.js Streams Guide: How to Handle Data with Examples

Streams pass data in parts, so the app stays fast. This article explains Node.js Streams and how to use them.…

Node.js REPL: The Complete Tutorial for Beginners

Node.js REPL runs JavaScript code in an instant test space inside your terminal. What is Node.js REPL? Node.js REPL is…

Node.js Hello World: Write Your First Program

In this quick tutorial, you will start Node.js tutorials with a Hello World program. You will learn how to set…

What is NodeJS? An Introduction to Node.js

What is Nodejs? Node.js is a powerful cross-platform JavaScript runtime that enables developers to execute JavaScript code on the server-side.…

Node JS Buffers Tutorial for Beginners and Pros

Node JS Buffers store raw binary data in memory. This guide shows how to create them, work with them, and…

Node js NPM: How to Publish and Install JS Packages

Node Package Manager (NPM) is an essential tool at the heart of the Node.js ecosystem. This is the defacto package…

Previous Article

Learn JSX in React: Syntax, Rules, and Examples

Next Article

PHP array_find_key: How it Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.