Create the Node.js First application Hello World

If we use PHP to write back-end code, you need Apache or Nginx's HTTP server, and with mod_php5 module and php-cgi.
From this point of view, the entire "receive HTTP requests and provide Web pages" needs simply do not need PHP to deal with.
But for Node.js, the concept is completely different. When using Node.js, we are not only implementing an application, but also implementing the entire HTTP server. In fact, our Web application and the corresponding Web server is basically the same.
Before we create the first "Hello, World!" Application for Node.js, let's start by understanding which parts of the Node.js application are:
  1. Introducing required modules: We can use the require directive to load the Node.js module.
  2. Create a server: The server can listen for client requests, similar to HTTP servers such as Apache and Nginx.
  3. The receiving request and the response request server are easy to create, the client can use the browser or the terminal to send the HTTP request, the server receives the request and returns the response data.

Create the Node.js application

Step 1, introduce the required module

We use the require command to load the http module and assign the instantiated HTTP to the variable http, as follows:
 var http = require ("http");

Step 2, create the server

Next we use the http.createServer () method to create the server and use the listen method to bind the 8888 port. Function through the 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) {

  // send HTTP header // HTTP status value: 200: OK
  // Content type: text / plain
  response.writeHead (200, {'Content-Type': 'text / plain'});

  // send response data "Hello World"
  response.end ('Hello World \ n');
 }) listen (8888);

 // The terminal prints the following information console.log ('Server running at http://127.0.0.1:8888/');
The above code we have completed a working HTTP server.
Use the node command to execute the above code:
 node server.js
 Server running at http://127.0.0.1:8888/
cmdrun
Next, open the browser to visit http://127.0.0.1:8888/, you will see a "Hello World" page.
nodejs-helloworld
Analyze the HTTP server for Node.js:
  • The first line requires (requires) Node.js comes with the http module, and assign it to the http variable.
  • Next we call the function provided by the http module: createServer. This function will return an object, this object has a method called listen, this method has a numeric parameter, specify the HTTP server to listen to the port number.

Gif instance demo

Then we show examples through the Gif example operation:


EmoticonEmoticon