Nodejs modules: Difference between revisions

From wikinotes
 
 
Line 19: Line 19:
</source>
</source>


<syntaxhighlight lang="javascript">
// you can also import only a subset of items
import { Buffer } from 'buffer';
// is similar to
const buffer = require('buffer');
const Buffer = buffer.Buffer;
</syntaxhighlight>


<source lang="javascript">
<source lang="javascript">

Latest revision as of 23:43, 31 July 2021

Documentation

module system https://nodejs.org/api/modules.html
expose https://nodejs.dev/learn/expose-functionality-from-a-nodejs-file-using-exports

Imports

// 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

~/.node_modules/
~/.node_libraries/
${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');
console.log(person);

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');
console.log(person.person);