Easily create nodejs server (1) : an example of a simple nodejs server
- 2020-05-07 19:11:18
- OfStack
Let's first implement a simple example, hello world.
This seems to be the case in section 1 of every language tutorial, and we are no exception.
First, we will create a project directory, which can be defined by ourselves. In this case, the directory is e:/nodetest/.
Since we're building a server, I'll name the first file server.js.
Enter the following code in server.js:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
Then we open cmd.
Navigate to the project directory with cd e:/nodetest/ and execute node server.js to run the file.
Then open a browser and visit http://localhost:8888/. You will see a page that says "Hello World".
In fact, this is a simple working server, just too simple to do anything, but never mind, follow me step by step, I will teach you how to build a complete available server.
In the next section, we will analyze the composition of this code.