What is node.js

January 15, 2017 by Vinicius Isola

Node.js is a runtime environment that can be used to build applications using the Javascript language outside the browser. It runs on top of the V8 engine, which is the engine that runs inside the Chromium and Chrome browsers.

Let’s learn more details about what all of this means.

Piece by Piece

V8 is an engine that interpret Javascript code. That means that you give it some Javascript text and it will execute it. And since it’s high performance, it will do it really fast in a very efficient way.

Even though V8 can execute Javascript, it doesn’t provide you with any APIs to do anything that’s really useful, like reading and writing to files, for example. It only knows how to interpret Javascript code according to the ECMAScript standards.

That’s where Node.js comes in. Node provides a set of APIs to do all sorts of useful things, including reading and writing from files in the disk. It also provides a runtime environment where you code can run in. This means that you can write a simple Javascript file and ask Node.js to run it.

Node.js is a command line tool, which means you have to run it from the terminal. That’s not a big deal because the command is really simple and there’s not a big learning curve there, just some extra typing.

The first thing you’ll need to do is go to nodejs.org, download and install node for your platform. And that’s it, you’re ready to go.

Simple application

So let’s just see how building a simple application in Node.js works.

Suppose that you want to write an application that reads text from files and print it on the console. The way it will work is that you’ll give a filename as the input and the application will just print out all the text on the console.

For this example, we’ll be using the following parts of the Node.js API:

The following snippet shows how you combine the API’s mentioned above to build this simple application. Save it on a file called print_output.js:

const fileSystem = require('fs');
const readline = require('readline');

const lineReader = readline.createInterface({
  input: fileSystem.createReadStream(process.argv[2])

let counter = 0;
lineReader.on('line', function (line) {
  console.log(counter + ': ' + line);

In the same directory, create a file called example.txt and put the following content inside it:

Some example text on the first line.
A second line with some more text.

That’s going to be the sample text file that our application will read.

After that run the following command from inside that directory:

$ node print_file.js example.txt

You’ll see that the application will print all lines in the file, each one in a new line and also prints the line number before them, using the counter variable. Here is an example output:

$ node print_file.js example.txt
1: Some example text on the first line.
2: A second line with some more text.

A few basic things that you’ll need to keep in mind when working with Node.js: