Easy to create Nodejs server (3): Code modularity _node.js

Source: Internet
Author: User

Most of the functional blocks of Nodejs are in the form of modules.

There is usually a unified entry index.js, and then a different module is called to complete the function we need.

Let's take a look at how to turn Server.js into a module for Index.js master files to use.

Copy Code code as follows:

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

"http" is a Nodejs module, and we request it in our code and assign the return value to a local variable. We can use this variable to invoke the object of the public method provided by the HTTP module, the variable name is not fixed, you can completely according to your preference to name the variable, but I suggest directly using the module name to do variable names, you can make the code more readable.

We change the code in Server.js this way, we put the code in the Start () function, and provide the code to other page references by Expors.

Copy Code code as follows:

var http = require ("http");
function Start () {
function onrequest (request, Response) {
Console.log ("Request received.");
Response.writehead ({"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 launch our HTTP in it, although the server's code is still in Server.js.

Create the Index.js file and write the following:

Copy Code code as follows:

var server = require ("./server");
Server.start ();

Execute node index.js

This allows you to put different parts of the application into separate files and connect them to each other by generating the modules.

In the next section, we'll take a look at routing

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.