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 -ycreatespackage.json, which lists your project's name, scripts and dependencies.npm install expressadds a package todependenciesand downloads it intonode_modules.npm install -D nodemonadds a dev dependency, used only during development.package-lock.jsonrecords exact versions so every install matches. Commit it; never commitnode_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?
node_modules is recreated by npm install from package.json and the lock file. Add it to .gitignore.
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.