Nodejs require module (file module/Core Module) and Path

Source: Internet
Author: User

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

The core module is compiled into binary code. You only need the require identifier When referencing it, for example (require ('net ')).

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

When the module is loaded, the search path of the module is not specified. If the file in '/home/ry/projects/foo. js' calls require ('bar. js'), node will search at the following position:
Copy codeThe 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 a module:
First, create the package. json file under the root of the folder, which identifies a main module. The content in a package. json may be as follows:
Copy codeThe Code is as follows:
{"Name": "some-library", "main": "./lib/some-library.js "}

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.