3. Node.js - First Application
3. Node.js - First Application
js - First Application
When learning a new language or a framework, the first application to write is a Hello
World program. Such a program displays the Hello World message. This illustrates the
basic syntax of the language and also serves to test whether the installation of the
language compiler has been correctly done or not. In this chapter, we shall write a Hello
World application in Node.js.
Console Application
Node.js has a command-line interface. Node.js runtime also allows you to execute
JavaScript code outside the browser. Hence, any JavaScript code can be run in a
command terminal with Node.js executable.
console.log("Hello World");
Open a powershell (or command prompt) terminal in the folder in which hello.js file is
present, and enter the following command −
Create server − A server which will listen to client's requests similar to Apache
HTTP Server.
Read request and return response − The server created in an earlier step
will read the HTTP request made by the client which can be a browser or a
console and return the response.
http.createServer(requestListener);
The requestlistener parameter is a function that executes whenever the server receives
a request from the client. This function processes the incoming request and forms a
server reponse.
The requestlistener function takes request HTTP request and response objects from
Node.js runtime, and returns a ServerResponse object.
The above function adds the status code and content-type headers to the
ServerResponse, and Hello World message.
server = http.createServer(listener);
server.listen(3000);
The program starts the Node.js server on the localhost, and goes in the listen mode at
port 3000. Now open a browser, and enter http://127.0.0.1:3000/ as the URL. The
browser displays the Hello World message as desired.