Index
Overview


Node.js modules are how we share JS code.

In this example we will look at local modules meaning local JS files (modules) that we create under the project directory/tree.

The module includes one or more "exports" which can than be imported (via "require") into another JS file.

Preparing for Examples


Initialize Project
>npm init


Module Example (Exporting Class)


Create Module (export)
Here we are creating a module with one exported class (meaning it can be used in another JS file).

Save this code into 'my-number.js'
//my-number.js
//module

class MyNumber {
	
	constructor(aNumber) {
		this.n = aNumber;
	}
	
	square() {
		return this.n * this.n;
	}
	
	cube() {
		return this.square() * this.n;
	}
	
	toString() {
		return `MyNumber(${this.n})`;
	}
	
}

//------------------------------------------
exports.MyNumber = MyNumber;
Use Module (import)
  • Import module using "require" keyword
  • Use class "MyNumber"

Save this code into "module-user1.js".
//module-user1.js

const
	tools = 
1
require('./my-number'), prn = (o) => console.log(o.toString()); let myNum = new
2
tools.MyNumber(3); prn(myNum); prn("Square: " + myNum.square()); prn("Cube: " + myNum.cube());
Run
>node module-user1
MyNumber(3)
Square: 9
Cube: 27

Module Example (Exporting Functions)


Create Module (export)
Here we are creating a module with two exported functions (meaning they can be used in another JS file).

Save this code into 'tools.js'.
//tools.js

const capitalize = (string) => {
	//Capitalized and return param.
	return string.charAt(0).toUpperCase() + string.slice(1);
}

const camelCaseToLabel = (camelCaseString) => {
	//'bestOperaSong' = 'Best Opera Song'
	const str = capitalize(camelCaseString);
	return str.replace(/([a-z])([A-Z])/g, '$1 $2');
}

//------------------------------------------
exports.capitalize = capitalize;
exports.camelCaseToLabel = camelCaseToLabel;
Use Module (import)
  • Import module using "require" keyword
  • Use function "capitalize" from module
  • Use function "camelCaseToLabel" from module

Save this code into "module-user2.js".
//module-user2.js

//"." for current (this) directory
const tools = 
1
require('./tools'); const name = 'asha'; console.log(`name: ${name}`); console.log(`name (capitalized): ${
2
tools.capitalize(name)}`); const varName = 'bestOperaSong'; console.log(`\nName: ${varName}`); console.log(`Label: ${
3
tools.camelCaseToLabel(varName)}`);
Run
Run the program normally
>node module-user2
name: asha
name (capitalized): Asha
Name: bestOperaSong
Label: Best Opera Song