乐闻世界logo
搜索文章和话题

What is the 'require' function in Node.js?

1个答案

1

The require function in Node.js is a crucial feature used to import another module or library within a script. In Node.js's module system, each file is treated as an independent module. When a module needs to use functionality or variables exported by another module, it uses the require function to load that module.

For instance, consider a file named math.js that defines an addition function:

javascript
// math.js file function add(x, y) { return x + y; } module.exports = add;

In another file, you can use the require function to access the add function:

javascript
// app.js file const add = require('./math'); console.log(add(5, 3)); // Output: 8

Specifically, require('./math') specifies importing the math.js file located in the same directory. By using module.exports, you define what the math.js file exports, which in this case is the add function. In app.js, you access this exported function via require and utilize it.

Node.js's modular mechanism greatly aids in organizing and reusing code, enhancing development efficiency while minimizing code redundancy.

2024年8月8日 02:49 回复

你的答案