node. JS Module

Source: Internet
Author: User

Often when you create a node. JS program, we need to divide the code into logical dependencies and organize it into multiple modules instead of putting the code in a single file. This is necessarily the same as in other languages, there are mechanisms like packages or modules that can be used. We look at how modules are created and used in node. js.

1. Single File module

--function(A, B)    {return a + b;}; var function (A, b) {    return A- b;}; --main.jsvar module = require (' module '); Console.log (Module.add (1, 2));

In the above code, we created a single module modules, which defines two functions add and sub, where add can be used externally (note that exports is used), and sub can only be used within a file. Main.js introduces module modules using require, and then you can use the Add function.

2. Catalogue Module

Now we define a operation directory and then create a index.js file under the directory. The content is the same as in the module.js above, and then place the operation directory in the Node_modules directory. You can use the Add function with require (' operation ') in Main.js. Note in the catalog

defines the module in the The file is set to Index.js file by default, if you want to use other files such as current.js as a module file, you should specify the main property in Package.json in the module directory as current.js, otherwise you will not be prompted to find the corresponding module .

node. JS Module

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.