Node.js Example Application

In our previous tutorial, we have successfully installed Node.js. Now it is time to write a simple Node.js application and climb the learning curve.

In this tutorial, we shall look into an example Node.js Application where we shall build an HTTP Server; and understand some of the basic components that go into making of a Node.js Application.

Example – Node.js HTTP Server

We shall create a basic HTTP server listening on a port.

You may use any text editor of your choice to create a script file with extension .js .

Create a file with the name node-js-example.js and copy the following content to it.

</>
Copy
// include http module in the file
var http = require('http');
// create a server listening on 8087
http.createServer(function (req, res) {
	// write the response and send it to the client
	res.writeHead(200, {'Content-Type': 'text/html'}); 
	res.write('Node.js says hello!');
	res.end();
}).listen(8087);

Once you have created the file, you may run it using node program from command line interface or terminal.

~$ node node-js-example.js

If you see nothing echoed back to the terminal, it is working fine, and a HTTP server has been started listening at port 8087. Now open any of the browser and hit the url http://localhost:8087/  to see the server responding with html page containing content Node.js says hello! .

Node.js Example Application

Let us look into the two lines of code that we have written in this example.

Node.js Example

This is just a mere example on how to get started with Node.js. In our subsequent tutorials, we shall learn about these concepts in details.