How to use require in nodejs

WBOY
Release: 2022-06-29 14:35:10
Original
2964 people have browsed it

In nodejs, require is used to load modules or files; the require function is a mechanism for synchronous loading at runtime. When this function uses a parameter, the parameter value can have the file name of the complete path module, or it can be the module name. When node loads the file, there will be a "require.cache" function to cache the file.

How to use require in nodejs

The operating environment of this article: Windows 10 system, nodejs version 12.19.0, Dell G3 computer.

How to use require in nodejs

In node, you can use the require() function to load modules.

The require function uses one parameter, and the parameter value can have a full path The file name of the module can also be the module name. When using the module provided in node, you only need to specify the module name in the require function.

The require function is a mechanism for synchronous loading at runtime (Copy the file), when node loads the file, there will be a require.cache function to cache the file

Whether the string contains a path. Such as the following example

1. No path (also called loading module): require('find')

2. There is path (also called loading file): require('./ find.js')

Loading module

Example:

require('find')
Copy after login

1. Node will first check whether the find module is a built-in module (nodejs built-in module Modules include fs, http, etc.), if not found, proceed to the next step

2. Search node_moludes from the current directory to see if there is a find.js file, if not found, proceed to the next step;

3. Find the find folder in node_moludes and look for the index.js file;

4. If there is no index.js file, go to package.json to find the main field, which corresponds to an entry path;

5. None of the above can be found, and an error is reported.

Loading files

Example:

require('./find')
Copy after login

1. node will first find the find.js file in the current directory;

2. Then search for the find.json file;

3. Search for index.js in the find folder in the current directory

4. If there is no index.js file, search in package.json main field, this field corresponds to an entry path;

Recommended learning: "nodejs video tutorial"

The above is the detailed content of How to use require in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!