Getting Started with Node.js

Node.js is a framework for building cross platform server side applications in Javascript. It is built on top of Google Chrome’s V8 Engine, which is a high performance Javascript engine written in C++.

Node.js is single threaded. It uses an event-driven architecture and is capable of asynchronous/non-blocking I/O.

This tutorial is aimed at beginners who are just starting out with node.js. In this tutorial you will -

  • Install node.js and npm in your system
  • Learn about node.js REPL
  • Run command line programs in node.js
  • Create a simple web server using node.js
  • Create a static file server using node.js

So, Let’s get started.

Installing Node.js

Head over to Node’s official website and download the latest stable version of node.js for your Operating System.

Node.js provides installers for Windows and Mac OS X. Download the installer, run it and follow the on-screen instructions to setup node.js.

For Linux platforms you need to download the Linux Binary(x86/x64), extract it and add the node.js executable to your system’s path variable.

Follow the steps below to install node.js in Linux. The current version of node.js at the time of writing this post is 6.10.3.

# Download the latest version of node.js
$ wget https://nodejs.org/dist/v6.10.3/node-v6.10.3-linux-x64.tar.xz

# Extract the tar file
$ tar xzvf node-v6.10.3-linux-x64.tar.xz

# Create a directory to store nodejs binary
$ sudo mkdir -p /usr/local/nodejs

# Move nodejs binary to the new directory
$ sudo mv node-v6.10.3-linux-x64/* /usr/local/nodejs 

Now you need to add node.js executable in the PATH variable. Add the following to your ~/.bashrc or ~/.bash_profile file and restart the terminal -

export PATH="$PATH:/usr/local/nodejs/bin"

Verify your installation by typing node in the terminal -

$ node
>

Node.js REPL

REPL stands for READ-EVAL-PRINT-LOOP. It creates a simple programming environment that reads user’s input, evaluates it, prints the result, and then repeats the same cycle.

Node.js comes with a built-in REPL terminal which works just like your browser’s console except that you can’t use DOM features with node.js REPL.

Open your terminal, type node and press enter to start the REPL terminal -

$ node
>

You can type any valid Javascript in the REPL and see the output instantly. Let’s try evaluating a simple expression -

> 121 + 392
513

You can use Javascript’s built-in methods like console.log -

> console.log("Hello World!")
Hello World!
undefined

You can create variables, write for loops and see the result instantly -

> var names = ["Ram", "Shyam", "Alice", "Bob"]
undefined
> for(var i = 0; i < names.length; i++) {
... console.log(names[i]);
... }
Ram
Shyam
Alice
Bob
undefined
>

You can create a function and call it from the terminal -

> var sum = function(x, y) {
...     return x+y;
... }
undefined
> sum(10,20)
30

Once you’re done experimenting, press Ctrl + C, or type .exit and then press enter to exit the REPL.

Running command line programs using Node.js

You can run command line programs in Node.js just like you run command line programs in Python or Ruby.

In the following example, I have written a simple program in node.js which takes the name of the user from command line arguments and greets him with a welcome message -

/*      
    Filename - greetMe.js
    Description - Node.js Command Line Program Demo
*/
var greeter = function(name) {
    console.log("Hello, " + name + "!");
}

var userName = null;
if(process.argv.length > 2) {
    userName = process.argv[2];
} else {
    userName = "Guest";
}

greeter(userName);

process.argv is an array that contains the command line arguments. If you run the above program with the following arguments -

$ node greetMe.js Rajeev

process.argv will look like -

[
'/usr/local/bin/node', 
'/Users/rajeevkumarsingh/node-getting-started/greetMe.js', 
'Rajeev'
]

The first and second items of process.argv array are -

  1. the path of node.js executable, and
  2. the absolute path of your program.

Any additional arguments supplied by the user comes after these two entries.

The above program prints Hello, Guest!, if no arguments are supplied, otherwise it prints Hello with the name supplied in the argument.

Creating a Simple Web Server in Node.js

Hello World Server

The following program is a simple web server written in node.js, which responds with Hello World to every request -

var http = require('http');

var server = http.createServer(function(req, res) {
    // Write response header
    res.writeHead(200, {"Content-Type": "text/html"});

    // Write the body of the response
    res.write("<html><body>");
    res.write("<h1>Hello, World</h1>");
    res.write("</body></html>");

    // Send the response
    res.end();
});

server.listen(3000, function() {
    console.log("Server is listening on port 3000");
});

The first statement var http = require('http'), imports the http module into the program and makes it accessible via the http variable. All the functions and objects of http module can be accessed via this single variable.

In the second statement, I’ve called http.createServer() method with an anonymous handler function to create a server.

The handler function function(req, res) is called on every http request. All the headers, parameters and body of the request can be accessed via the req parameter.

The res parameter is a handle which is used to write and send the response back to the browser. In the handler function above, We simply send a 200 OK response with a Hello World html body.

Finally, I’ve called server.listen() to start listening for requests on the specified port number.

Let’s now run the above program using -

$ node hello-world-server.js

Open your web browser and go to http://localhost:3000. You should see the following output -

Node.js Getting Started Hello World Web Server

That was cool! We wrote a web server in just 10 lines of code. In the next section, we’ll write another web server which serves static files from the project’s working directory.

Static File Server

In the following program, I’ve created a web server which takes the path of a file in the request, tries to read the file and responds with the file’s contents if the read was successful, otherwise, returns a 500 Server Error response.

For example, if the request is sent to http://localhost:3000/hello.txt, the server will look for hello.txt in the project’s working directory and respond with it’s contents.

var http = require('http');
var fs = require('fs');
var path = require('path');

var server = http.createServer(function(req, res) {
    var filePath = path.join('.', req.url);
    fs.readFile(filePath, function(err, data) {
        if(err) {
            console.log(err);
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end(err.message);
        } else {
            res.writeHead(200, {'Content-Type' : 'text/plain'})
            res.end(data);
        }
    });
});

server.listen(3000, function() {
    console.log("Server is listening on port 3000");
});

I have used two more modules in the above program - fs and path.

The fs module is the node.js filesystem module which provides apis for several filesystem operations like creating files, making directories, listing files, reading files etc.

The path module provides apis for working with file and directory paths.

After receiving a request, I first join req.url with . to make all paths relative to the project’s working directory, and then try to read the file using fs.readFile() method.

The fs.readFile() methods takes the file’s path and a callback function. It reads entire contents of the file asynchronously, and then calls the callback function with two arguments - err and data.

If the file was read successfully, err object will be null and data will contain the file’s contents, otherwise, err object will contain the details of the error and data will be null.

In the callback function, if err object is non-null, We send a 500 Server Error response with the error message, otherwise return the contents of the file.

Let’s now run the server and see the output. I have a file named hello.txt in the same folder as the above static-file-server.js file. If I open http://localhost:3000/hello.txt in the web browser, the server responds with the contents of hello.txt -

Node Static File Server

If I enter a random file name that doesn’t exist, the server sends back the error message to the browser -

Node Static File Server Error

What’s next?

The popularity of node.js has increased drastically in recent years. The main USP of node.js is its event-driven architecture and the fact that developers can use a single language, Javascript in both backend and frontend.

I encourage you to checkout the following tutorials to understand and learn more about node.js and it’s ecosystem -

Also, Please feel free to ask any questions that you might have in the comment section below.