nodejs--Module

Source: Internet
Author: User

The client can split all the JavaScript code into several JS files and then merge the JS files in the browser. But in Nodejs, all functions are divided in modules. Each module is a JS file, The scope of the global variable or function defined in each module is also scoped to the module, and only the exports object can be used to pass it to the outside:

Exports.printfoo = function () {return ' foo '};

In the above code, we define a Printfoo function that returns the Foo string inside the function, and we use the exports object to make the Printfoo function accessible outside the module.

When referencing a module, we can use the Require function, for example, after saving this module file with the Frintfoo function as a foo.js file, you can access the Printfoo function in the module by using the following code.

1 var // loading the Foo.js module via the foo.js file path; 2 // accessing the Printfoo function within the Foo.js module

In the first line of code, we read the Foo,js module and refer to it through the Foo object, and in the second line of code we refer to the module through the Foo object, and in the second line of code we access the Printfoo function within the module through the Foo object.

The console window will output the string "foo".

In Nodejs, you can use the Require function directly and set the module name to the parameters of the Require function to refer to these modules.

nodejs--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.