Nodejs modules

From wikinotes


module system


// relative and absolute filepath imports
const foo = require('./foo')
const bar = require('../bar')
const baz = require('/home/me/baz')
// you can also import only a subset of items
import { Buffer } from 'buffer';

// is similar to
const buffer = require('buffer');
const Buffer = buffer.Buffer;
// ${PROJECT}/node_modules/* imports

The ${NODE_PATH} is a PATH-style environment variable where modules can be loaded from.

// ${NODE_PATH} modules

Global Folders

${PREFIX}/lib/node/  # the configured 'node_prefix'

Expose functions

When a module is required, it returns that module's module.exports object.
You can customize this import behaviour in two ways:

1. assign the module.exports object itself

// person.js
module.exports = { a: 1 };  // set imported object

// other.js
const person = require('./person.js');

2. assign a property on module.exports object

// person.js
exports.person = { a: 1 };  // set property on imported object

// other.js
const person = require('./person.js');