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