How to set up a Node module

Setting up a Node module involves initializing a project with npm init, installing dependencies, and creating a JavaScript file (like index.js) to write code. You can use require() or import to include modules. This setup enables efficient project management and code reuse in Node.js.

Step 1: Install Node.js and npm

If not already installed, download from https://nodejs.org

To check if it’s installed:

Open terminal and run:


node -v
npm -v

Step 2: Initialize Your Node Project

Open terminal and run:


npm init

Or use the shortcut:


npm init -y

This creates a package.json file.

Step 3: Create Your Entry File

Create a file like index.js:


 // index.js
console.log('Hello, Node.js!');

Step 4: Install Node Modules

Install any package, e.g., Express:

Open terminal and run:


npm install express

This creates a node_modules/ folder and updates package.json.

Step 5: Use the Installed Module

Example using Express:

index.js


// index.js
const express = require('express');
const app = express();

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

app.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

Step 6: Run Your App


node index.js

Common Files Created

  • package.json – Project metadata and dependencies
  • package-lock.json – Exact version control of installed packages
  • node_modules/ – Directory with installed dependencies