Once the environment is set up, you can start to build a simple Web server (node drive).
First of all, Nodejs is still written with JS. Let's take a look at the instance code on node's website.
var http = require (' http '); http.createserver(function(req,res) { Res.writehead ( 200,{' content-type ': ' Text/plain '}); Res.end (' Holle,nodejs ');}). Listen (8080, ' 127.0.0.1 '); Console.log (' Server running at http://127.0.0.1:8080/');
After the encoding is complete, save (the JS file name: server.js).
The Server.js file is then called through the cmd command tool.
Use the CD command to open the directory where the Server.js ( command: cd path ) , node command executes the server.js file (command:node server.js).
command line output log information indicating that the server was created successfully.
This allows the node engine to create a simple server based on the above code.
test: Open Browser, address bar input: 127.0.0.1:8080, you can see the page display Holle,nodejs
PS: Note here that sometimes the command line output the log information, but in the browser to enter the address but can not find the page. Side dishes also encountered such a problem, and then try to change the port number, the problem has been resolved. So side-dish analysis, if the port is occupied will not find the port, node will display the log information, but the service has not been created.
A simple analysis of this code
A >
var http = require (' http ');
Create an HTTP module.
B >
Http.createserver (function (req,res) {
Res.writehead (200,{' content-type ': ' Text/plain ');
Res.end (' Holle,nodejs ');
})
Create a server from the HTTP module.
Three >
Listen (8080, ' 127.0.0.1 ');
8080 port requests are monitored via listen.
Four >
function (req,res) {
Res.writehead (200,{' content-type ': ' Text/plain ');
Res.end (' Holle,nodejs ');
}
Server callback function: Req request, res response.
After the server receives the request,
Returns the content and state through the res.writehead definition, where a status code of 200 is returned, and the contents are Text/plain plain text.
Returns content by Res.end definition.
Such a simple service is done, there is a response, there is a request (the request is temporarily not added).
Nodejs Learning Notes < two > simple node server