Node.js First Application

We assume that, Node.js is installed on your computer.Let try to display "Helllo Node.js" in a web browser.

A node.js web application have the following three parts.

Part 1 - Import Required Module In Node.js "require" directive is used to load a Node.js module.

Part 2 - Create Server http.createServer() method is used to create a server instance similar to Apache HTTP Server.

Part 3 - Read request and return response: Server created in the second step (using http.createServer()) will read HTTP request made by client which can be a browser or console and return the response.

Create a Node.js file named "myfirstnode.js", and add the following code.

var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Helllo Node.js'); }).listen(4004);

Save the file on your computer on following location.

C:\Users\Your Name\myfirstnode.js

Run the Node.js Program

Go to location where Node.js file has been save.

C:/Users/Your Name>node myfirstnode.js

Now open browser, and type the following in browser.

http://localhost:4004