Hello world application in Node.js

Hello world application in Node.js Without ExpressJS

Once you have downloaded and installed Node.js on your computer, lets try to display “Hello World” in a web browser.

Create file Node.js with file name firstprogram.js

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello World!');
}).listen(8080);

Code Explanation:

  1. The basic functionality of the “require” function is that it reads a JavaScript file, executes the file, and then proceeds to return an object. Using this object, one can then use the various functionalities available in the module
    called by the require function. So in our case, since we want to use the functionality of http and we are using the require(http) command.

  2. In this 2nd line of code, we are creating a server application which is based on a simple function. This function is called, whenever a request is made to our server application.

  3. When a request is received, we are asking our function to return a “Hello World” response to the client. The writeHead function is used to send header data to the client and while the end function will close the connection to the client.

  4. We are then using the server.listen function to make our server application listen to client requests on port no 7000. You can specify any available port over here.

Executing the code

  1. Save the file on your computer: C:\Users\Your Name\ firstprogram.js

  2. In the command prompt, navigate to the folder where the file is stored. Enter the command Node firstprogram.js

    C:\Users\Your Name\node firstprogram.js

  3. Now, your computer works as a server! If anyone tries to access your computer on port 8080, they will get a “Hello World!” message in return!

  4. Start your internet browser, and type in the address: http://localhost:8080

    OUT PUT : Hello World

Summary

  • We have seen the installation of Node.js via the msi installation module which is available on the Node.js website. This installation installs the necessary modules which are required to run a Node.js application on the client.

  • Node.js can also be installed via a package manager. The package manager for windows is known as Chocolatey. By running some simple commands in the command prompt, the Chocolatey package manager automatically downloads the necessary files and then installs them on the client machine.

  • A simple Node.js application consists of creating a server which listens on a particular port. When a request comes to the server, the client automatically sends a ‘Hello World’ response to the client.

Leave a Reply

Your email address will not be published. Required fields are marked *