In Node.js, the require()
function is used to include modules that exist in separate files. When you call require()
with the name of a module, it returns an object representing the module.
The basic functionality of require()
can be thought of as follows:
fs
, http
, etc.), the module is returned.require()
will look for the module in the following places:node_modules
folderOnce the module is found, require()
will:
require.cache
object. If it is, the cached version of the module will be returned.require()
will:exports
, module
, and require
objects as argumentsrequire.cache
objectHere’s an example of how you might use require()
in a Node.js script:
const fs = require('fs'); fs.readFile('/path/to/file', (err, data) => { if (err) throw err; console.log(data); });
In this example, the fs
module is included and used to read a file.
Here’s another example, suppose you have a file called math.js that contains some math functions:
// math.js exports.add = (a, b) => { return a + b; }; exports.subtract = (a, b) => { return a - b; };
You can include and use the functions in math.js
in another file like this:
// main.js const math = require('./math'); console.log(math.add(1, 2)); // 3 console.log(math.subtract(5, 3)); // 2
The require()
function will look for the math.js
file in the same directory as main.js
, load the code in the file, and return an object with the functions specified using the exports
object. In this case, the returned object has the add
and subtract
functions, which can be called as shown in the example.
require()
can also be used to include built-in Node.js modules and third-party modules installed in the node_modules
directory. For example, to include the fs
module, which provides functions for interacting with the file system, you can use:
const fs = require('fs');