Tutorial by Examples

A module can be "imported", or otherwise "required" by the require() function. For example, to load the http module that ships with Node.js, the following can be used: const http = require('http'); Aside from modules that are shipped with the runtime, you can also require mod...
Node provides the module.exports interface to expose functions and variables to other files. The most simple way to do so is to export only one object (function or variable), as shown in the first example. hello-world.js module.exports = function(subject) { console.log('Hello ' + subject); }...
In development, you may find that using require() on the same module multiple times always returns the same module, even if you have made changes to that file. This is because modules are cached the first time they are loaded, and any subsequent module loads will load from the cache. To get around ...
You can also reference an object to publicly export and continuously append methods to that object: const auth = module.exports = {} const config = require('../config') const request = require('request') auth.email = function (data, callback) { // Authenticate with an email address } au...
NodeJS executes the module only the first time you require it. Any further require functions will re-use the same Object, thus not executing the code in the module another time. Also Node caches the modules first time they are loaded using require. This reduces the number of file reads and helps to...
Modules can be required without using relative paths by putting them in a special directory called node_modules. For example, to require a module called foo from a file index.js, you can use the following directory structure: index.js \- node_modules \- foo |- foo.js \- package.json ...
Modules can be split across many .js files in the same folder. An example in a my_module folder: function_one.js module.exports = function() { return 1; } function_two.js module.exports = function() { return 2; } index.js exports.f_one = require('./function_one.js'); exports.f_two...

Page 1 of 1