What is Node.js?

What is Node.js?

This post is assumes you are familiar with JavaScript, if you are not please see my blog post "What is JavaScript".


Node.js is a very popular cross-platform, open source, JavaScript runtime built on top of Google Chrome's V8 JavaScript engine which developers can use to create a variety of applications. The majority of  Node.js applications; however, are designed to be web based applications. One of the advantages of Node.js compared to other frameworks is the event based model/loop which is common practice in most (if not all) Node.js applications.

Since Node.js uses and event based loop, it is not inherently blocked from executing code just because another snippet of code is running. Due to the usage of an event based loop, code may not always execute as expected, for example if we are able to read a file from the operating, using the built in file system module, from the operating system with the following code:

const fs = require('fs');

fs.readFile('someFile.txt', (text) => {
  console.log(text);
});
Read data from file using the fs module

Upon running the code shown above, we should expect to see the contents of someFile.txt in the console/terminal of your computer; however, if we modified the code slightly to:

const fs = require('fs');

fs.readFile('someFile.txt', (text) => {
  console.log(text);
});

console.log('other log');
Read data from file using the fs module and log 'other log'

When we run the code, we would see other log in the console/terminal of your computer before we see the contents of someFile.txt.

The reason behind seeing other log in the console/terminal of your computer before seeing the contents of someFile.txt is due to Node.js running the two proccesses, reading the file someFile.txt and outputting other log to the console/terminal, concurrently. Though processes running concurrently can be beneficial, it can also lead to issues if you are not mindful.

One potential downside to the event based loop Node.js utilizes; however, is that Node.js runs on a single thread. While there are ways to make Node.js run on multiple threads, some may find it not very intuitive. If you want Node.js to run on multiple threads you can use a different module known as child_process. While we will not describe the specifics of child_process you can read more about it in the official documentation.

Hopefully this gives you some insight into Node.js, if you want to download Node.js you can do so here.