Create a new text file named "Hello.js" and enter the following
1 //loading the HTTP module2 varHTTP = require (' http ');3 //building an HTTP server4 varServer = Http.createserver (function(request,response) {5Response.writehead (200,{' content-type ': ' Text/plain '});6Response.Write (' Hello world! ');7 Response.End ();8 });9 //start the HTTP server and start listening on the 3000 port numberTenServer.listen (3000); One //Print logs in the console AConsole.log (' Server running at http://127.0.0.1:3000 ');
In the Command line window, "CD" to the current directory, and then execute the following command
Node Hello.js
If you can print "Server running at http://127.0.0.1:3000" in the console, our first program is already working properly.
Then open the browser, enter in the address bar
http://127.0.0.1:3000
Code Description:
In the browser we will see "Hello world!".
The 2nd line loads the HTTP module first, and we need this module when we create the HTTP server.
The 4th line is to create an HTTP server,
Line 5th writes an HTTP header to the HTTP response,
Line 6th is written to the HTTP body, which is what we see in the browser,
The 7th line is to end the HTTP response, return to the browser,
Line 10th starts the service and listens on Port 3000.
The 12th line prints the log.
node. JS Getting Started (ii) first program Hello World