In Node.js, modules are used to divide code and enhance maintainability. Export modules through module.exports and import modules through require(). Single values (export keyword) or objects (module.exports) can be exported. Module paths can be absolute or relative. The module follows the singleton pattern and is cached after import. Dynamic modification can be achieved by changing module.exports.
How to use modules in Node.js
In Node.js, modules are independent files. Functions from other modules can be exported and imported. Using modules improves the maintainability and modularity of your code by organizing it into smaller reusable units.
How to export a module
To export a module, you can use the module.exports
object. module.exports
is a special object that represents the export value of the current module. To export a function, you assign it to module.exports
:
<code class="javascript">// my-module.js function sayHello() { console.log("Hello!"); } module.exports = sayHello;</code>
How to import a module
To import a module, you use require()
function. require()
The function receives the path or name of a module as a parameter and returns the object that exports the module:
<code class="javascript">// app.js const sayHello = require("./my-module"); sayHello(); // 输出: "Hello!"</code>
Importing and exporting multiple values
You can use the module.exports
object to export multiple values, or you can use the export
keyword to export a single value or variable:
<code class="javascript">// my-module.js export function sayHello() { console.log("Hello!"); } export const name = "John";</code>
<code class="javascript">// app.js import { sayHello, name } from "./my-module"; sayHello(); // 输出: "Hello!" console.log(name); // 输出: "John"</code>
Module path
Module paths can be absolute or relative to the current directory. If the path does not start with /
or ./
, Node.js will try to load the module from the node_modules
directory.
Note:
module.exports
object. The above is the detailed content of How to use modules in nodejs. For more information, please follow other related articles on the PHP Chinese website!