Most of the functional blocks of nodejs exist in the form of modules.
Usually there will be a unified entry index.js, and then different modules are called to complete the functions we need.
Let's first look at how to turn server.js into a module for the index.js main file to be used.
The code copy is as follows:
var http = require("http");
...
http.createServer(...);
"http" is a module that comes with nodejs. 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, I suggest using the module name directly as the variable name, which can make the code readable more.
We change the code in server.js in this way, we put the code into the start() function, and provide the code to other page references through exposures.
The code copy is as follows:
var http = require("http");
function start() {
function onRequest(request, response) {
console.log("Request received.");
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;
This way, we can now create our main file index.js and start our HTTP in it, although the server's code is still in server.js.
Create an index.js file and write the following:
The code copy is as follows:
var server = require("./server");
server.start();
Execute node index.js
Doing so allows you to put different parts of the application into different files and connect them together by generating modules.
We need to learn about routing in the next section