Node.js Creating Your First Application
When we use PHP to write backend code, we need an HTTP server like Apache or Nginx, along with the mod_php5 module and php-cgi.
From this perspective, the task of "receiving HTTP requests and serving web pages" does not need PHP to handle.
However, the concept is entirely different with Node.js. Using Node.js, we are not only implementing an application but also creating the entire HTTP server. In fact, our web application and the corresponding web server are essentially the same.
Before we create our first Node.js "Hello, World!" application, let's understand the components that make up a Node.js application:
-
Import required modules: We can use the require directive to load Node.js modules.
-
Create a server: The server can listen for client requests, similar to HTTP servers like Apache and Nginx.
-
Receive and respond to requests: Creating a server is easy; clients can send HTTP requests using a browser or terminal, and the server responds with data upon receiving the request.
Creating a Node.js Application
Step 1: Import Required Modules
We use the require directive to load the http module and assign the instantiated HTTP to the variable http, as shown below:
var http = require("http");
Step 2: Create a Server
Next, we use the http.createServer() method to create a server and bind it to port 8888 using the listen method. The function receives and responds to data via the request and response parameters.
Create a file named server.js in the root directory of your project and enter the following code:
var http = require('http');
http.createServer(function (request, response) {
// Send HTTP headers
// HTTP status code: 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);
// Terminal prints the following information
console.log('Server running at http://127.0.0.1:8888/');
The above code completes a functional HTTP server.
Execute the code using the node command:
node server.js
Server running at http://127.0.0.1:8888/
Next, open your browser and visit http://127.0.0.1:8888/, and you will see a webpage displaying "Hello World".
Analyzing the Node.js HTTP Server:
The first line requests (requires) the Node.js built-in http module and assigns it to the http variable.
Next, we call the function provided by the http module: createServer. This function returns an object that has a method called listen, which takes a numeric parameter specifying the port number that the HTTP server listens to.
Gif Demonstration
Next, we will demonstrate the example operation through a Gif image: