CommonJS is the way to package our JavaScript code into modules for the Node runtime.

brain

In simple terms: a way to break a single js script into many.

Examples

stam.js

const num = 42;
module.exports = { num }; // { num } is a shorthand for { num: num }

index.js

const bamba = require('./stam');
bamba.num; // 42

if you want to import only num:

index.js

const number = require('./stam').number;
number; // 42

you can also use the destructure syntax

index.js

const { number } = require('./stam');
number; // 42

functions and classes

stam.js

function sayHi() { console.log('hi'); }

function sayBye() { console.log('bye'); }

class Person {
	constructor(_fname, _lname) {
		this.fname = _fname;
		this.lname = _lname;
	}
}

module.exports = { sayHi, sayBye, Person };

importing them exactly the same way

index.js

const { sayHi, sayBye, Person } = require('./stam');

sayHi();
sayBye();
new Person('avi', 'biter');

Core modules (builtin)

index.js

const fs = require('fs');

Installed modules

only after installing express by executing:

npm install express

you can run

const express = require('express');