Node.js: What is it and how does it work?

What is Node.js??

If you have been coding in JavaScript, you have been using Node.js this whole time. Well, technically this isn’t true. When were coding in JavaScript we are using node and the npm library, but it’s not really Node.js. When we talk about Node.js, we are implying that we are using it as a way to create server and interact with our database on the backend. So far while doing projects I have only used JavaScript on the front end, in order to avoid refreshing the page, while still rendering new information on the page. With Node.js we are able to use JavaScript on the backend in order to handle requests to different urls. First I’ll talk a little about how it works and the difference between conventional servers, then give a brief overview of a test server, and finally discuss the pros and cons of a Node.js backend.

How does it work?

First of all just like other languages node comes with packages and modules. These are libraries of functions that we can import from npm (node package manager) into our code and utilize. If you have node installed on your computer, then you already have some basic modules installed. These are how we create a simple server, but I’ll get to that later.

If you are familiar with JavaScript, then you know it is asynchronous and single threaded. The single thread is the event loop which is responsible for running all functions and requests. The asynchronous behavior is extremely important when using node, because it guarantees that the event loop is never blocked by a synchronous function.

source: https://webapplog.com/event-loop/

Even though there is only one event loop, when a request is made the loop passes the request to an asynchronous function which does the work. When this function is done and a response is returned, it can then be passed back to the event loop to be executed by the callback and sent to the user. If the functions were synchronous then the event loop would get locked up with one clients request and response, and all other clients would have to wait till that client was done. Because of the the asynchronous nature of JavaScript, the applications using node can handle many requests happening at the same time. This means that when programming in Node.js it is important to always keep in mind that the functions being written are not synchronous. It is also very important to catch errors on the server before it is passed back to the client. This prevents any errors from getting to the event loop which could crash the program and all clients would suffer.

How does this affect users?

What does this mean for the user? Is Node.js faster than other backends? The answer is that it isn’t necessarily faster. The main benefit of a Node.js server is that it can handle much more traffic than a conventional server. Other servers are multithreaded which means that each client, when connected to the website, gets their own thread. Each thread takes care of the requests made by their client. When you think about this it makes sense. Each thread takes care of one user and there is no crossover between clients, so technically they should affect each other. But this is not true. In reality there are limited threads available on a server. Therefore when there are more requests than there are threads, the client must wait for a thread to open up. This can lead to a slow down for other users, and can lead to server crashing if it gets too many requests at once.

With Node.js, while there is only one thread (the event loop), when a request is made the event loop can pass it to another function to execute and then when it gets completed and sent back to the user the interaction ends. There doesn’t need to be an open connection (thread) at all times because it is event driven. This means that a Node.js server can accommodate more clients, with the same amount of memory, than another multithreaded server.

What database should I be using?

In my personal opinion, it makes sense to use a document based NoSQL database such as MongoDB. The reason being is that if you are using Node.js, then you are probably utilizing a full stack JavaScript framework. With a document based database it is extremely easy to read and write data because all the information can be stored and passed as JSON. From front to back there doesn’t have to be any translation, since the frontend and backend both talk JSON when using full stack JavaScript. However, it is possible use traditional SQL databases such as MySQL. The data being read or written just needs to be transformed so that it can be stored and rendered to the client. This is done with methods like .json() and JSON.stringify().

Basic Server

So how do we get started with Node.js? The simplest example is this done using the node http package provided on npm. With this module it is possible to create the most basic server. Here is an example that would start a server on localhost:8080, and would display the message “My first Node.js server!”

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('My first Node.js server!');
}).listen(8080);

This is very basic and in order to get more useful routing, Node.js frameworks are used. Express.js is the most popular framework used today because it is easy to create RESTful routes, and provide access to the database through client requests.

What are the downsides?

Because it is single threaded if your app requires a lot of computation or a lot of algorithms this can slow down the event loop. This means that all clients could experience delays because they are all waiting for the same computation to finish and free up the event loop. Another problem that can occur is callback hell. This happens when there are so many callbacks nested within each other that the code becomes unreadable or hard to maintain. This can be avoided but it takes practice to learn how to think in this asynchronous way. Another problem is with the modules available from npm. Since Node.js is relatively new packages and modules are constantly being created or updated, therefore its hard to have consistency between different websites and apps. For example it would be much easier for a Ruby and Rails programmer to transition from different jobs and different projects because it stresses convention over configuration. There is no conventions for apps or websites written with Node.js. Accessing the database can also become a problem. This is because the database can only handle so many requests at once. This can be fixed if a queue system is used for database queries.

When should I use it/learn it?

It is best used for websites that have open connections such as chat or streaming. It is much easier to integrate websockets and realtime streaming into Node.js, because it was kept in mind when it was designed. It is also good when you know that your website or app will have a lot of client traffic, because it can handle many more connections with less memory used on the server. Overall I think it is good to at least have a basic understanding of how Node.js is used in a fullstack program. While it is the “hot” thing now to create MEAN stack applications or websites, there are many companies that use other frameworks and other backend languages such as PHP and Ruby. If you’re planning to work in start-ups, then I would highly recommend getting a firm grasp on Node.js. Personally I’m gonna try to build some simple projects just to get used to the basic concepts of this backend. And I suggest you do to!

Sources: