Home / Node.js / Lesson 2

Modules and npm

Beginner 8 min read Lesson 2 of 6

Start a folder:

mkdir api-demo && cd api-demo
npm init -y

That writes package.json. Add "type": "module" if you want import/export (ESM). Without it, Node treats .js as CommonJS (require/module.exports). Both are valid; this course uses ESM because it matches frontend JS.

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

// index.js
import { add } from './math.js';
console.log(add(2, 3));

Local files need a path (./math.js). Bare names (express) come from npm:

npm install express

That updates package.json and package-lock.json and fills node_modules. Commit the lockfile. Do not commit node_modules.

Scripts: "start": "node index.js" then npm start.