Node.js Basics (Modules, CommonJS, npm)

Node.js is a powerful and popular JavaScript runtime built on Chrome's V8 JavaScript engine. One of the key features of Node.js is its module system, which allows you to organize your code into reusable chunks. This chapter will cover the basics of Node.js modules, CommonJS, and npm, giving you a solid foundation to build and manage Node.js applications effectively.

Node.js Modules

Node.js uses modules to manage dependencies and organize code. There are three types of modules in Node.js:

  • Built-in Modules: Provided by Node.js itself.
  • Custom Modules: Created by developers.
  • Third-party Modules: Installed via npm.

Built-in Modules

Node.js comes with a variety of built-in modules for performing common tasks. Here are some examples:

  • fs: File System operations.
  • http: Creating HTTP servers.
  • path: Handling and transforming file paths.

Example using the fs module:

				
					const fs = require('fs');

// Reading a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log('File contents:', data);
});

				
			

Output:

				
					File contents: [contents of example.txt]

				
			

Custom Modules

You can create your own modules to organize your code. A module in Node.js is simply a file. You use the module.exports object to expose functions or variables from your module.

Example:

Create a file math.js:

				
					function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

module.exports = {
    add,
    subtract
};

				
			

In another file app.js:

				
					const math = require('./math');

console.log('Add:', math.add(1, 2));
console.log('Subtract:', math.subtract(2, 1));

				
			

Output:

				
					Add: 3
Subtract: 1

				
			

CommonJS

What is CommonJS?

CommonJS is a module specification used by Node.js. It defines a simple way to organize code into modules, making it easier to manage and reuse.

Using 'require' and 'module.exports'

  • require: Used to import modules.
  • module.exports: Used to export functions, objects, or primitives from a module.

Example:

Create a file greet.js:

				
					function greet(name) {
    return `Hello, ${name}!`;
}

module.exports = greet;

				
			

In another file app.js:

				
					const greet = require('./greet');

console.log(greet('World'));

				
			

Output:

				
					Hello, World!

				
			

Example: Creating and Using a Custom Module

Create a file calculator.js:

				
					function multiply(a, b) {
    return a * b;
}

function divide(a, b) {
    if (b === 0) {
        throw new Error('Division by zero');
    }
    return a / b;
}

module.exports = {
    multiply,
    divide
};

				
			

In another file app.js:

				
					const calculator = require('./calculator');

console.log('Multiply:', calculator.multiply(6, 3));
console.log('Divide:', calculator.divide(6, 3));

				
			

Output:

				
					Multiply: 18
Divide: 2

				
			

NPM (Node Package Manager)

What is NPM?

NPM is the default package manager for Node.js. It allows you to install, manage, and share JavaScript packages. NPM also helps in managing project dependencies through the package.json file.

Initializing a Project with npm init

To create a new Node.js project and initialize it with npm, use the following command:

				
					npm init

				
			

This command will prompt you for several details about your project, such as the name, version, and entry point. You can use npm init -y to skip the prompts and create a package.json file with default values.

Installing Packages

To install a package, use the npm install command. For example, to install Express.js:

				
					npm install express

				
			

This will create a node_modules directory and a package-lock.json file if they don’t already exist. The installed package will be listed in your package.json under dependencies.

Using package.json

The package.json file is the heart of any Node.js project. It contains metadata about the project and lists its dependencies. Here’s an example of a package.json file:

				
					{
  "name": "my-node-app",
  "version": "1.0.0",
  "description": "A sample Node.js project",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {},
  "author": "Your Name",
  "license": "ISC"
}

				
			

Semantic Versioning

NPM uses semantic versioning to manage package versions. Version numbers follow the format MAJOR.MINOR.PATCH:

  • MAJOR: Breaking changes.
  • MINOR: New features, no breaking changes.
  • PATCH: Bug fixes, no breaking changes.

Example versioning:

  • ^1.0.0: Compatible with 1.x.x.
  • ~1.0.0: Compatible with 1.0.x.

Managing Dependencies

1. Installing a specific version:

				
					npm install express@4.16.0

				
			

2. Updating dependencies:

				
					npm update

				
			

3. Removing a package:

				
					npm uninstall express

				
			

Useful NPM Commands

1. Install packages:

				
					npm install

				
			

2. Install a package globally:

				
					npm uninstall express

				
			

3. List installed packages:

				
					npm list

				
			

4. View outdated packages:

				
					npm uninstall express

				
			

Understanding the basics of Node.js modules, CommonJS, and npm is crucial for developing efficient and maintainable applications. Node.js's module system, powered by CommonJS, allows you to organize your code into reusable pieces. npm, the Node Package Manager, simplifies managing dependencies and sharing code with the community. With these tools and concepts, you are well-equipped to start building robust Node.js applications.This chapter has covered everything from creating custom modules to managing dependencies with npm, providing a comprehensive guide to the foundational aspects of Node.js development. Happy Coding! 🚀

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India