Node.js · Lesson 2 of 7

Modules & npm

Splitting code into modules with import/export, package.json and installing packages.

Real projects split code into modules — one file per responsibility. Modern Node uses ES modules (import/export). Add "type": "module" to package.json to use them. Older code uses CommonJS (require/module.exports); you'll see both at work.

package.json and npm

  • npm init -y creates package.json, which lists your project's name, scripts and dependencies.
  • npm install express adds a package to dependencies and downloads it into node_modules.
  • npm install -D nodemon adds a dev dependency, used only during development.
  • package-lock.json records exact versions so every install matches. Commit it; never commit node_modules.

Example code

Run with Node.js 20+
// salary.js
export function monthly(lpa) {
  return Math.round((lpa * 100000) / 12);
}

// app.js   (package.json has "type": "module")
import { monthly } from "./salary.js";

const offers = [4.5, 6, 8.2];
for (const lpa of offers) {
  console.log(lpa + " LPA = Rs " + monthly(lpa) + " per month");
}

Output

4.5 LPA = Rs 37500 per month
6 LPA = Rs 50000 per month
8.2 LPA = Rs 68333 per month

Save the code in a file such as app.js and run node app.js. For Express lessons, run npm install express first. Names and data are fictional.

Key points

  • Use import/export (ES modules) for new code.
  • package.json lists dependencies and scripts.
  • Commit package-lock.json, not node_modules.
  • Use npm scripts such as npm run dev to run common commands.

Quick check

Which file should you NOT commit to Git?

Practice task

Create a module with two functions (add GST to a price, and format a number as rupees), import both in app.js and print the results.

Interview corner

What is the difference between dependencies and devDependencies?

dependencies are needed to run the app in production (express, a database driver). devDependencies are only needed while developing or testing (nodemon, jest, eslint).

CommonJS vs ES modules?

CommonJS uses require and module.exports and loads synchronously; it's the older Node default. ES modules use import/export, are the JavaScript standard, and work in browsers and modern Node.

Further reading

Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.

Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.