Before creating the actual "Hello world" application in Node.js, see the main parts of the Node.js program. A Node.js program includes the following important sections:
Modules needed : We use require directive to load a module Node.js.
Create Server : A server listens to requests from the client side similar to the Apache HTTP Server.
Read the request and return the response : The server created easily will read the HTTP requests by the client from the browser or console screen to return the response.
Create Node.js application
Step 1: Import the necessary modules
We use the require directive to load the http modules and return the expressions to the http variable as follows:
var http = require ( "http" );
Step 2: Create Server
Next step, we will create http and call http.createServer () method to create a new Server and return a Server Instance and then mount it on port 8081. Transfer it to the request and response parameters. Write the following example paragraph about the "Hello World" program.
http . createServer ( function ( request , response ) { // Gui HTTP header cua request // HTTP Status: 200 : OK // Content Type: text/plain response . writeHead ( 200 , { 'Content-Type' : 'text/plain' }); // Gui phan than cua response, bao gom "Hello World" response . end ( 'Hello Worldn' ); }). listen ( 8081 ); // Man hinh Console se in thong bao console . log ( 'Server dang chay tai http://127.0.0.1:8081/' );
This code is enough for creating an HTTP Server to listen and wait for the local 8081 response.
Step 3: Check Request & Response
Put steps 1 and 2 together in a file with the name main.js and turn on HTTP Server as follows:
var http = require ( "http" ); http . createServer ( function ( request , response ) { // Gui HTTP header cua request // HTTP Status: 200 : OK // Content Type: text/plain response . writeHead ( 200 , { 'Content-Type' : 'text/plain' }); // Gui phan than cua response, bao gom "Hello World" response . end ( 'Hello Worldn' ); }). listen ( 8081 ); // Man hinh Console se in thong bao console . log ( 'Server dang chay tai http://127.0.0.1:8081/' );
Start Server and see the results as follows:
$ node main . js
Check the result. Server is turned on.
Server is running http://127.0.0.1:8081/
Create a request to a Node.js Server
Open http://127.0.0.1:8081/ in any browser and see the results:.
Congratulations on creating the first Node.js application successfully. Follow up on the next chapters to get a deeper understanding of Node.js.
According to Tutorialspoint
Previous lesson: Module in Node.js
Next article: REPL Terminal in Node.js
ncG1vNJzZmismaXArq3KnmWcp51ktaa4y6hksKeiobFuvNGonquZnWK2r3nNqJueoqM%3D