Node.js Module

By Xah Lee. Date: .

Here is sample lib file.

// file lib1.js

exports.f1 = (x => (x + 1));
exports.c1 = 456;

// in nodejs, this exports the names f1 an c1

To export names, attach them as properties of the object exports

Use require to load a module, and attach all exported names to a given name. Like this:

// load lib1.js
// give it a name m
const m = require('./lib1.js');

console.log( m.f1(3) === 4); // true
console.log( m.c1 === 456 ); // true

if you have a object name or class name, say

const xx = { a: 1, b: 2, };

and you want to export xx without a extra namespace. you can do

module.exports = xx;

Example:

// lib2.js

const xx =  {
a: 1,
b: 2,
};

module.exports = xx;
const yy = require('./lib2.js');

console.log( yy.a === 1 ); // true

https://nodejs.org/docs/latest-v10.x/api/modules.html#modules_modules

See also: Import/Export

back to Node.js Tutorial

back to JavaScript in Depth

BUY ΣJS JavaScript in Depth