Node.js is a JavaScript runtime environment based on the Chrome V8 engine, which can help us build and run efficient web applications. The core idea of Node.js is modularization, which means encapsulating a function or code block in an independent module that can be referenced and reused in other modules. In this article, we will explore how to set up modules in Node.js.
In Node.js, each JavaScript file is a module, and a module can contain several variables, functions, objects, etc. Variables, functions, etc. defined in a module can only be used within the module and must be exported when using other modules.
The following is an example module namedexample.js
:
const sayHello = name => { console.log(`Hello, ${name}!`); }; module.exports = { sayHello, };
This module defines a function namedsayHello
, and Export it so that other modules can use it.
In Node.js, to import a module, you need to use therequire
function, which can pass in the path of the module , returns an object, the content of the object is the variables, functions, etc. exported by the module.
const example = require('./example.js'); example.sayHello('Tom');
In the above code, first use therequire
function to import theexample.js
module. After importing, we can call the function exported by the modulesayHello
, and pass in a parameterTom
.
After usingmodule.exports
to export variables, functions, etc., other modules can userequire
The function references the module, but variables, functions, etc. defined in the module will not be exported by default. If you want to export a variable or function, you can assign it to themodule.exports
object or add it to the object.
const name = 'Tom'; const sayHello = () => { console.log(`Hello, ${name}!`); }; module.exports = { name, sayHello, };
In the above code, we exported the variablename
and the functionsayHello
. These two variables can be referenced or called in other modules.
In Node.js, there are a large number of third-party modules available, you can use thenpm
command line tool Download and install these modules. After installation, you can import third-party modules just like your own modules by specifying their names.
For example, to install and use thelodash
library:
const _ = require('lodash'); const arr = [1, 3, 2, 4, 2]; const uniqArr = _.uniq(arr); console.log(uniqArr); // [1, 3, 2, 4]
In the above code, we first installed ## using thenpm
command line tool #lodash, then imported the module through the
requirefunction, and finally used the function
uniqin the module to deduplicate the array
arr.
The above is the detailed content of How to set up nodejs module. For more information, please follow other related articles on the PHP Chinese website!