All You Need To Know About Node.js – Getting Started

I have written a blog on Introduction to Node.js. Please check that link to know some basics.

In this tutorial, We will look in to the following topics:

  • Node.js Dev environment set up
  • Hello World node.js web application, which prints or responds with ‘Hello World’
  • Explanation on the hello.js file

After this tutorial, you should be able to:

  • create a simple web server using node.js , which prints ‘Hello World’.
  • Understand the parts of the hello.js file.

You have to install the node.js in your machine. Please follow the instructions from https://nodejs.org/en/download/ to install node.js.

After installing, run the following command to verify the installation.
node --version

It should print the version of your node.js.

nodeversion

Developing the hello world program in node.js:

Now we are going to develop a small program that will print ‘Hello World from Node!’. Please note this is just a program, NOT a web server.

    1. Create a file called ‘helloWorld.js’, Enter the following line:
      console.log("Hello, World from Node!")
    2. Execute using node helloWorld.js and enter in the node REPL.
    3. You can see the message.

repl_nodejs

Developing a web server using node.js and responding with ‘Hello World from Node.js web server!’:

Now we are going to develop a small web server using node.js. Our server will simply respond  ‘Hello World from Node.js web server!’ when you make a request. The file is called ‘helloServer.js

var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World from Node.js web server!");
response.end();
}).listen(8090);

Node.js uses lots of inbuilt modules to accomplish various tasks for example file access, interacting with operating system services etc.

We have used such a module called ‘http’ to develop a web server which will listen to 8090 port and emits the message ‘Hello World from Node.js web server!’.

It is simple? Let us run and see whether we have developed a web application or not.

Just run ‘node helloServer.js’ and hit enter.
node helloServer.js

servermsg

Now try to browse it from the browser and see what happens! http://localhost:8090/

serverres

So we have developed a small standalone (helloWorld.js) program and a web server(helloServer.js) and successfully executed it.

Leave a Reply

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