Home > Web Front-end > JS Tutorial > body text

Nodejs require module (file module/core module) and path introduction_Basic knowledge

WBOY
Release: 2016-05-16 17:43:43
Original
1466 people have browsed it

In nodejs, modules can be roughly divided into core modules and file modules.

The core module is compiled into binary code, and only requires the require indicator when referencing it, such as (require('net')).

File module refers to js file, json file or .node file. When referencing the file module, add the file path: /.../.../xxx.js represents the absolute path, ./xxx.js represents the relative path (xxx.js in the same folder), . ./ represents the upper-level directory. If neither /.../, ../ nor ./ is added, the module is either a core module or loaded from a node_modules folder.

When neither ./ ../ /.../ is specified when loading the module, the search path for loading the module. If the file in '/home/ry/projects/foo.js' calls require('bar.js'), node will search in the following locations:

Copy code The code is as follows:

/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js

Folder as module:
First create at the root of the folder package.json file, which identifies a main module. The content in a package.json may be as follows:
Copy code The code is as follows:

{ " name" : "some-library", "main" : "./lib/some-library.js" }

If this is under a folder ./some-library, then require ('./some-library') will try to load ./some-library/lib/some-library.js. If there is no package.json file in this directory, node will try to load index.js or index from this directory. .node files. For example, if there is no package.json file above, then when require('./some-library'), will try to load the following file :
Copy code The code is as follows:

./some-library/index.js
./some-library/index.node
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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template