Nodejs require module (file module/core module) and path Introduction _ Basics

Source: Internet
Author: User
In Nodejs, modules can be divided into core modules and file modules.

The core module is compiled into binary code, which can be referenced only with require notation, such as (Require (' net ')).

File module refers to a JS file, a JSON file, or a. node file. The path to add the file after referencing the file module:/.../.../xxx.js represents the absolute path,./xxx.js represents the relative path (Xxx.js under the same folder), ... /Represents the previous level of the directory. If you do not add/.../、.. /If not, the module is either a core module or is loaded from a Node_modules folder.

When loading a module, it does not indicate./. //.../, load the search path of the module. If the file in '/home/ry/projects/foo.js ' calls require (' bar.js '), node will search in the following location:
Copy Code code 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, the Package.json file is created under the root of the folder, which identifies a main module. The contents of a Package.json may be as follows:
Copy Code code as follows:

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

If this is in a folder./some-library, then require ('./some-library ') will attempt to load./some-library/lib/ Some-library.js If there are no Package.json files in this directory, node will attempt to load index.js or Index.node files from this directory. For example, if there is no Package.json file on top, then require ('./some-library ') will attempt to load the following file
Copy Code code 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.