Require in node.js
The require() function allows you to include modules into your programs. You can import built-in node.js modules, community-based modules(node_modules) and local modules.
The function require() returns an object, which references the value of module.exports for a given file, when the require is invoked, a sequences of tasks are happened:
Require will look for file/directory in the following order:
Built-in module Node.js modules (like: fs module), show in Example-1
Modules in node_modules folder.
If the module name has a ./, / or ../, it will look for the directory in the given path. It matches the extensions: *.js, *.json and *.node.
Note : The require is a function that takes one argument called path, Node.js.
How to Use require() function
Importing a local Coustom module or module
const myLocalModule = require('./path/myLocalModules');
Importing a JSON file
const jsonData = require('./path/jsonFile.json');
Importing a module from Node.js built-in modules or node_modules.
const crypto = require('crypto');
➤ Example 1: myMod.js
const fs = require('fs'); fs.readFile('./myfile.txt', 'utf-8', (err, data) => { if(err) { throw err; } console.log('data: ', data); });
In Example-1 the path is "./myfile".
Comments