Node.js Module

By Xah Lee. Date: .

Here's 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: JS: Import/Export

back to Node.js Tutorial

back to JavaScript in Depth

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog