Home  >  Article  >  Web Front-end  >  Easily create nodejs server (3): Code modularization_node.js

Easily create nodejs server (3): Code modularization_node.js

WBOY
WBOYOriginal
2016-05-16 16:25:521255browse

Most of the function blocks of nodejs exist in the form of modules.

Usually there is a unified entrance 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 use.

Copy code The code 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 preference. However, I recommend using the module name directly as the variable name, which can make the code More readable.

Let’s change the code in server.js in this way. We put the code in the start() function and provide the code to other pages for reference through expors.

Copy code The code 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;

With this, 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 code The code is as follows:

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

Execute node index.js

This way you can put different parts of the application into different files and connect them together by generating modules.

In the next section we will learn about routing

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn