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