Easy creation of nodejs servers (3): Code modularization and nodejs Modularization

Source: Internet
Author: User

Easy creation of nodejs servers (3): Code modularization and nodejs Modularization

Most node. js functional blocks exist in the form of modules.

Usually there is a unified entry index. js, and then different modules are called to complete the functions we need.

Let's take a look at how to turn server. js into a module for the index. js main file to be used.

Copy codeThe Code is as follows:
Var http = require ("http ");
...
Http. createServer (...);

"Http" is a built-in node. js module. We request it in our code and assign the return value to a local variable. We can use this variable to call the object of the public method provided by the http module. The variable name is not fixed. You can name this variable according to your preferences, however, we recommend that you directly use the module name as the variable name to make the code more readable.

Modify the code in server. js in this way. Put the code in the start () function and provide the code to other pages for reference through expors.

Copy codeThe Code is as follows:
Var http = require ("http ");
Function start (){
Function onRequest (request, response ){
Console. log ("Request received ed .");
Response. writeHead (200, {"Content-Type": "text/plain "});
Response. write ("Hello World ");
Response. end ();
}
Http. createServer (onRequest). listen (8888 );
Console. log ("Server has started .");
}
Exports. start = start;

In this way, we can now create our main file index. js and start our HTTP in it, although the server code is still in server. js.

Create the index. js file and write the following content:

Copy codeThe Code is as follows:
Var server = require ("./server ");
Server. start ();

Run node index. js

In this way, different parts of the application can be put into different files and connected together by generating modules.

Next, let's take a look at the Routing

Related Article

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.