Latest web development tutorials

Node.js to create the first application

If we use PHP to write back-end code, you need Apache or Nginx HTTP server, and accompanied mod_php5 modules and php-cgi.

From this perspective, the entire demand "to receive HTTP requests and provide Web pages" of PHP do not need to deal with.

But for Node.js, a concept completely different. When using Node.js, we not only in the realization of an application, but also realized the whole HTTP server. In fact, our Web application and the corresponding Web server is basically the same.

Before the first application we created Node.js "! Hello, World", let us first understand what Node.js application is made of several parts:

  1. The introduction of required modules: we can use requireinstruction to load Node.js modules.

  2. Create Server: The server can listen for client requests, like Apache, Nginx and other HTTP server.

  3. The serverreceives the request and respond to requests very easy to create, the client can use the browser or terminal sends an HTTP request, the server receives the request and returns a response data.

Create Node.js applications

Step one, the introduction of required modules

We userequire instruction to load http module, and instantiate HTTP assigned to the variable http, examples are as follows:

var http = require("http");

Step one, create a server

Next we use http.createServer () method to create a server, and uses method bindings listen 8888 port. Function by request, response parameters to receive and respond to data.

Examples are as follows, create a file called server.js in the root directory of your project, and write the following code:

var http = require('http');

http.createServer(function (request, response) {

	// 发送 HTTP 头部 
	// HTTP 状态值: 200 : OK
	// 内容类型: text/plain
	response.writeHead(200, {'Content-Type': 'text/plain'});

	// 发送响应数据 "Hello World"
	response.end('Hello World\n');

// 终端打印如下信息
console.log('Server running at');

The above code we have completed a working HTTP server.

Using thenode command to perform the above code:

node server.js
Server running at


Next, open the browser to access, you'll see that says "Hello World" page.


Analysis Node.js HTTP server:

  • The first line of the request (require) Node.js comes http module, and assign it to a variable http.
  • Next we call the function module provides http: createServer. This function returns an object that has a method called listen, this method has a numeric parameter specifying the HTTP server listening port number.

Gif examples demonstrate

Next we show you examples by Gif Pictured actions: