node. JS Tutorial 04-Module system

Source: Internet
Author: User

Objective:

Node. JS's module system is similar to a file reference in C/C + +, you can declare objects, or you can define class creation objects.

It's easy for everyone to understand.

Defined:

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

Modules are a basic part of the node. JS application, and the files and modules are one by one corresponding.

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

Example one:

This example demonstrates the creation of a method in hello.js and then calls the method in the main program Main.js .

In node. js, creating a module is very simple, so let's just do it. The steps are as follows:

  Step 1: in the E:\NodejsDemo folder, create a "hello.js" file with the following code:

1 exports function () {2     console.log ("Welcome to My blog!") ); 3 }

In the above code, we use the exports object and welcome as the interface for the current hello.js module.

In this way, in other modules (JS file), using the require command, the current JS file is introduced, you can directly access the welcome .

  Step 2: in the same directory, we create a "main.js" file, as the main program to execute, introduce the Hello.js file, execute the Welcome method, the code is as follows:

1 var require ('./hello ');//introduction of Hello.js Module (file)  2 hello.welcome (); Accessing the Welcome function in the Hello.js file

In the above code, we use the Require function to introduce the Hello.js file.

We then put the introduced Hello.js module into a local variable "Hello".

Finally, we call the Welcome function using the local variable "Hello", which accesses the welcome external interface function in the Hello.js module.

  Note: When the Hello.js module is introduced here, we do not add a suffix, "./" means the current directory, and node. JS has the default suffix ". js".

  Step 3: start DOS, enter the directory, execute "node Main.js" to run the main program:

OK, we find that after we call the Welcome method, we execute the Welcome function created in the Hello.js file.

In this case, it is very simple to understand what I have said at the outset. The focus is on exports and require.

    • Declaration in Hello.js- exports.welcome = function () {...}
    • Main.js in the first sentence-introduced hello.js:var Hello = require ('./hello ');

Require commands us before "node. JS Tutorial 02-Classic Hello World" has been touched.

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.

There is no feeling that this example is much like java/. NET to define classes, declare objects, invoke methods?

Example two:

JS Daniel knows that in JavaScript, we can "define classes, instantiate objects."

So what do we do if we want to encapsulate an object in a module?

According to the example above, we divert: Define a person class, introduce instantiation, assign a value, and finally call the function.

Step 1: Create a "person.js" file, as the module file to be introduced, the code is as follows:

1 functionPerson () {2     varname;3      This. SetName =function(_name) {4Name =_name;5     }6     7     varURL;8      This. SetUrl =function(_url) {9URL =_url;Ten     } One      A      This. SayHello =function(){ -Console.log ("Welcome to my blog!\n" +URL); -Console.log ("My name is" + name + ".) Nice to meet you! "); the     } - } -  -Module.exports = person;

In the code above, we created a person object that contains two parameters to be assigned and an output function.

The point is the last sentence: module.exports = person;

The only change to the module interface is to use module.exports = person instead of Exports.world = function() {} .

When the module is referenced externally, its interface object is the person object to be exported, not the original exports.

  Step 2: Create the main program "Main.js", introduce the Person.js module, initialize and invoke the instance, the code is as follows:

1  var person = require ('./person '); 2 3  varnew person ();  4 person.setname ("guying"); 5 person.seturl ("Http://www.cnblogs.com/LonelyShadow"); 6 Person.sayhello ();

In the above code, we first introduce the "Person.js" module file to the local person object in line 1th.

The 3rd line instantiates the person object and stores the instance in the local person object.

4–5 Line, assign the name and URL parameters to this person object.

Line 6th, access the SayHello () function of the person object, and output the result.

Ps: So far, do you think this thing is too similar to class and object? O (∩_∩) o haha ~

Where are the server modules placed?

You may have noticed that we have already used modules in the code in "node. JS Tutorial 03-Creating HTTP Servers." Like this:

1 var http = require ("http"); 2 ... 3 http.createserver (function() {});

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.

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

Since there are 4 classes of modules (native modules and 3 file modules) in node. js, although the Require method is extremely simple, internal loading is very complex and its loading priority is different. As shown in the following:

  Loading from the file module cache

Although the native module has a different priority than the file module, it does not take precedence over loading the existing module from the cache of the file module.

  Load from native module

The priority level of the native module is second only to the priority of the file module cache.

The Require method first checks whether the module is in the list of native modules after parsing the file name.

In the case of HTTP modules, although there is a Http/http.js/http.node/http.json file in the directory, require ("http") is not loaded from these files, but is loaded from the native module.

The native module also has a buffer, which is also preferentially loaded from the buffer. If the buffer has not been loaded, then the loading mode of the native module is called to load and execute.

  Load from File

When the file module cache does not exist and is not a native module, node. js resolves the parameters passed in by the Require method and loads the actual file from the file system.

The packing and compilation details in the loading process are described in the previous section, where we will describe in detail the process of finding a file module, with some details worth knowing.

The Require method accepts the following types of parameters:

    • HTTP, FS, path, and so on, native modules.
    • ./mod or.. /mod, relative path to the file module.
    • /pathtomodule/mod, the absolute path of the file module.
    • MoD, non-native module of the file module.

node. JS Tutorial 04-Module system

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.