"Node. js" Module system, function

Source: Internet
Author: User

node. JS provides a simple modular system to allow node. js files to be called each other.

A node. js file is a module that may be JavaScript code, JSON, or compiled C/s extensions.

Create a module

In node. js, creating a module is very simple, as follows we create a ' hello.js ' file with the following code:

var hello = require ('./hello '); Hello.world ();

In the above example, the code require ('./hello ') introduces the Hello.js file in the current directory (./is the current directory, and node. js is the default suffix JS).

node. JS provides exports and require two objects , where exports is the interface that the module exposes, and require is used to obtain an interface from the outside of a module, the exports object of the acquired module.

Next we'll create the Hello.js file with the following code:

function () {  console.log (' Hello World ');}

In the example above, Hello.js uses World as the interface for the module through the exports object, loading the module through require ('./hello ') in Main.js, and then directly accessing the Hello The member function of the exports object in. js.

Sometimes we just want to encapsulate an object into a module in the following format:

function () {  // ...}

For example:

              function Hello () {var name;   This function (thyname) {         = thyname;     };       This function () {         console.log (' Hello ' + name);      = Hello;

This allows you to get the object directly :

var Hello = require ('./hello 'new  Hello (); Hello.setname (' byvoid   ‘
Where are the modules on the server?

node. js comes with a module called "http" , which we request in our code and assign the return value to a local variable.

This turns our local variables into an object that has the public methods provided by all HTTP modules.

var http = require ("http"), .... Http.createserver (...);

The file lookup policy in node. JS's require method is as follows:

"Node. js" Module system, function

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.