What is Node.js: Understanding how it works and how to get started

What is Node.js: Understanding how it works and how to get started

Node.js is an open-source, cross-platform runtime environment that lets you run JavaScript on the server side. This software’s architecture enables efficient data transfers, making it a popular choice for building real time and scalable applications.

This tutorial will teach you the basics of Node.js, including how it works and its practical applications. We will also cover how to set it up on your server so you can get started quickly. 

Introduction to Node.js

Traditionally, JavaScript only ran on the front end since the runtime was only available in web browsers such as Google Chrome. This makes the programming language viable for building a client-side application, much like a dynamic website.

Ryan Dahl created Node.js back in 2009 as a lightweight and responsive back end runtime environment for JavaScript. This software allows developers to use the scripting language as the server-side code.

Using JavaScript on the server side lets developers write both the front and back end in the same language. It helps streamline developement and maintenance since they can reuse the same code.

Furthermore, developing the back end in JavaScript allows your app to benefit from Node.js’ asynchronous programming model. At its core, this architecture allows your web service to serve multiple user requests more efficiently.

We will talk more about this concept in the following section.

How does Node.js work

To understand the working principle of Node.js, you must understand the following important terms.

Non-blocking I/O model

To handle a user request, traditional servers like Apache and Tomcat use a thread that can serve one client at a time. Once you reach the maximum number of threads, a new request must wait for the existing ones to finish their task.

Threads that are still processing user requests will block input from new clients and won’t forward output to external services like APIs or databases. It might lead to bottlenecks during traffic peaks with many concurrent connections.

Non-blocking paradigms mean that Node.js’ single thread can receive and forward a new request without waiting for the current one to complete. Such a system is called asynchronous architecture.

Asynchronous architecture

Synchronous architecture processes client requests in an order, meaning the web server will complete the current operation before starting a new one.

Meanwhile, an application with asynchronous architecture will begin a new operation while waiting for the results of other operations. Once it receives a response, the web server returns the data to the client.

Asynchronous architecture is suitable for applications that require fetching data from other services, like application programming interfaces (APIs) or databases. Instead of being idle, the web server can process new requests while waiting for responses.

While excellent for input-output (I/O) tasks, this architecture makes Node.js more CPU-intensive since it only uses a single thread to handle multiple requests.

Event-driven

In Node.js, events are signals indicating that a certain action has occurred. For example, they might trigger a new operation or task completion.

Events are integral for enabling the asynchronous model. They operate in a loop, instructing Node.js how to handle the request flow.

Upon receiving a new client request, the event loop starts. Then, Node.js forwards the request to the appropriate external service, like an API. Once your server receives the data, a new event triggers a callback function.

A callback function executes another function when a specific condition or asynchronous operation is completed. It enables the web server to process requests and send responses to the client.

V8 JavaScript engine

At the core of Node.js is the V8 JavaScript engine, which parses and executes the scripting language. In other words, it lets your back end server execute JavaScript code outside a web browser.

Google originally developed this engine for Google Chrome. Later on, Node.js adopts this technology to enable JavaScript to run independently on top of Node.js.

Advantages of using Node.js

After understanding Node.js’ mechanism, let’s explore how this model can benefit your web application development.

  • Speed. Node.js’ asynchronous architecture handles multiple I/O operations more efficiently, resulting in a more responsive application. It also makes the runtime suitable for real time data fetching. 
  • Error-handling mechanism. The built-in error objects give users more flexibility in handling numerous issues. They allow developers to gain more detailed insights about the error for more efficient troubleshooting and processing. 
  • Development efficiency. Node.js allows developers to use JavaScript anywhere for full-stack development. It makes development easier since the code works seamlessly across the back and front end. 
  • Rich ecosystem. Users can install various modules via Node Package Manager (NPM) to easily add new functionalities to their Node.js applications without writing them from scratch.
  • Flexibility and scalability. Developers can use Node.js with other frameworks and operating systems. They can also scale the runtime using different approaches, like installing a load balancer or setting up microservices.
  • Open source. Node.js’s source code is accessible to all users, and its creators push for transparency, innovation, and customization. This runtime also has strong community support. 

What you can do with Node.js

Here are several Node.js use cases that can benefit from the runtime’s responsive I/O operation and asynchronous architecture:

  • Live chatting and streaming. Chatting and streaming platforms involve a lot of I/O operations as users send and receive data in real time. Node.js’ efficient processing helps minimize delay since it can process client requests simultaneously.
  • Data stream. Node.js can quickly fetch and push information from external sources, making it perfectly suitable for real time data streams. This technology’s applications include stock market and system monitoring. 
  • Server proxies. A server proxy is an intermediary between clients and the host server, typically used for load balancing or traffic filtering. Node.js ensures client requests and the server’s response travels smoothly. 
  • RESTful APIs. Node.js is commonly used to create RESTful APIs that enable applications to use external services over a network. 
  • Single-page applications (SPAs). SPAs like Gmail and PayPal update client-facing data in real time without a manual refresh. Node.js enables the data from the host server to transfer quickly.

Node.js vs other back end technologies

In addition to Node.js, developers use a myriad of technologies to develop back end applications. Here are some popular ones and their comparison with the JavaScrpt runtime.

.NET

.NET is a web application framework popular for large-scale enterprise applications. Despite being a Microsoft product, this technology is compatible with Linux and MacOS. However, many developers report it is more responsive when running on Windows.

.NET supports object-oriented programming languages like C++, C#, and VB. This capability makes the framework suitable for developers who want to take advantage of those languages’ flexibility and features.

The .NET framework adopts the multi-threaded approach with an asynchronous processing model. This architecture is suitable if your service mainly involves complex, CPU-intensive tasks.

However, .NET applications are more difficult to develop. If your web services involve a lot of external calls, using Node.js to build the back end is more efficient.

Ruby on Rails

Ruby on Rails is a web development framework written in the Ruby object-oriented language. It follows the model-view-controller (MVC) approach, which provides a defined structure for your application.

This structure allows developers to efficiently build a functional application prototype and include additional features afterward. This makes Ruby on Rails ideal for iterative projects, where developers divide a project into smaller tasks.

Despite the simplicity, the MVC approach makes Ruby on Rails less flexible than Node.js. Meanwhile, the JavaScript runtime lets you develop an application as microservices, making it highly modular and scalable.

Since Ruby on Rails is multi-threaded, it is more suitable for a system with multiple cores. However, it doesn’t work asynchronously, potentially slowing down your application’s performance if it requires frequent I/O calls.

Django

Django is a web development framework for Python, a highly versatile and flexible programming language. It is popular for building applications or services that process large amounts of data.

Unlike Node.js, which is ideal for building microservices, developers commonly use Django to develop a monolithic application. In this model, you write your program’s services in a single large code base.

While somewhat scalable, Django monolithic applications are less flexible than microservices. However, this framework’s model-view-template (MVT) model helps developers build services more efficiently using smaller, reusable components.

Django uses synchronous, multi-threading architecture, which makes it suitable for a data-intensive monolithic application and a system with multiple cores.

Laravel

Laravel offers various templates commonly used in a web application, including authentication, authorization, and notifications.

Laravel’s templates and simple syntax make coding a web application more accessible, especially for beginners. Furthermore, it follows the MVC architecture that helps developers quickly maintain and modify the code base.

However, many users report that Laravel offers suboptimal performance out of the box compared to other back end technologies. This means you must fine-tune the configuration or set up additional software like Octane to improve its speed.

If your application involves a lot of real time data streams and I/O operations, Laravel might not be ideal because it uses a multi-threaded blocking mechanism.

Pro Tip

When choosing back end technologies, many developers recommend prioritizing familiarity and project requirements. While frameworks perform differently, you may overlook a significant impact on real-world usage.

Node Package Manager (NPM)

Node Package Manager (NPM) is a tool for installing software, like modules or dependencies, for JavaScript applications. It helps improve Node.js development efficiency by allowing users to access additional components from a single place.

Important! NPM can refer to either the utility developers use to download the packages or the repository where users share their modules.

The NPM repository currently houses millions of packages and modules, including the highly popular Lodash JavaScript library. You can also download other frameworks from the repository, like Express.js and Mocha.js.

Downloading and managing packages from NPM use your system’s command-line interface. By default, this utility is automatically configured after you install Node.js, which we will explain in the following section.

Getting started with Node.js

Now that you understand how Node.js can benefit your web development projects let’s dive into the steps to set it up. For this tutorial, we will demonstrate how to do so on a Hostinger virtual private server (VPS) running Ubuntu 22.04.

Installing Node.js

Hostinger VPS users can easily install Node.js on Ubuntu without commands using the operating system template.

After purchasing the Node.js VPS hosting plan, simply complete the onboarding tasks and wait until the configuration process is complete. It should take a few minutes, and our system will automatically set up the runtime environment on your server.

Chose a different VPS plan?

If you already have an active VPS hosting plan from Hostinger, you can still install Node.js without commands using the operating system template.

For other hosting providers, you must manually install Node.js using commands. Here are the steps to follow to do this:

  1. Connect to your server using the PuTTY SSH client or command-line tools like Terminal. We recommend doing so as a superuser instead of root.
  2. Update your system’s package by running these commands one by one:
sudo apt update && sudo apt upgrade
  1. Now, enter the following to install Node.js:
sudo apt install nodejs -y 
  1. Your package manager should also automatically install NPM. However, run the following to ensure the tool is configured correctly:
sudo apt install npm -y 
  1. Confirm the installation by querying the node version using the following command:
node -v

When developing a Node.js application locally, you must install the runtime on your local machine. The easiest way to do so is by downloading the prebuilt installer based on your operating system from the official release page.

Building and Running Applications with Node.js

The steps for building Node.js applications are similar to those for other web developments. Here is what you need to do:

  1. Install Node.js, NPM, VSCode code editor, and Live Server extension
  2. Create a folder for your project. Open VSCodeFileOpen Folder and select your new directory.
  3. Navigate to your VSCode terminal and run the following command to create a configuration file for your project:
npm init
  1. Enter the required information. Once finished, you should see package.json in VSCode’s explorer window.  
  2. From the main screen, select New File and create a new project file. For example, name it app.js
  3. Write your application code. For testing, you can create a simple Hello World program. Hit Ctrl + S to save it. 
  1. From your VSCode terminal, run node followed by your JS file name to start your application:
node app.js

It’s all done! In our scenario, you can access the application by adding the localhost address alongside the designated port number to your web browser.

The steps are similar regardless of your operating system.

To deploy it to the live site, upload the project file using commands, git, or secure file transfer protocol (SFTP).

Working with Modules and Dependencies

NPM lets you easily manage modules and dependencies to improve your Node.js application functionality.

The package.json file in your project folder contains information about your application’s dependencies. Instead of managing the packages individually, you can call package.json in bulk.

For example, running the following command will update all dependencies listed in the file:

npm install

You can check for outdated packages and install updates using a single command. This capability makes the process more efficient and maintains consistency across different project environments.

Moreover, Node.js lets you automatically list new modules or dependencies in packages.json during installation using the –save option. This command looks as follows:

npm install software-name --save

Node.js includes internal modules that come pre-configured when you install the runtime environment. You can also install external ones from the npm repository.

To load a module in your application code, use the require function. For example, the following snippet calls express.js and assigns it as the express variable:

const express = require('express')

The built-in modules vary depending on your Node.js version. To check which ones are installed on your current system, use the following command:

npm list -g

Need help with JavaScript?

Use the Kodee AI assistant to assist you in writing JavaScript code and generating npm commands for developing your application.

Node.js frameworks and libraries

In practical scenarios, developers don’t rely solely on Node.js to build an application. They incorporate a framework to create the project structure and a library to add functions easily. Here are some of the most popular options.

Express.js

Express.js or Express is the most widely used Node.js framework. It is favored for its minimalistic and unopinionated model, which allows developers to structure their application code without restriction.

This framework’s notable features include versatile, built-in request handling. It lets developers quickly call a specific function based on HTTP requests’ method and URL patterns. Without Express, such a mechanism would only be possible using a lengthy code.

Furthermore, the Express.js framework enables developers to use middleware—software that modifies requests and responses during transmission. For example, it allows you to authenticate, log, or limit transferred data.

React.js

React.js is a front end JavaScript library that is used to develop a website or web application’s user interface (UI). While relatively new, it has gained massive popularity due to its focus on ease of use and beginner-friendliness.

Like other libraries, React provides a set of reusable components that help developers effortlessly build a complex interface. What sets it apart is the use of JSX syntax, which allows you to write HTML-like markup in JavaScript.

React helps improve your website or web application loading speed using a virtual document object model (DOM). This feature enables web browsers to render only the changed UI sections rather than the entire page, making the process more efficient.

Socket.io

The JavaScript library Socket.io provides features for handling data transmission in real time, making it a popular alternative for developing I/O-intensive services like games, live stream platforms, and chat applications.

Socket.io enables your Node.js application to respond to clients without waiting for their requests. In messaging applications, for example, this functionality allows group members to receive a message from a user automatically.

Socket.io offers a more reliable and responsive way to enable two-way client communication than traditional WebSockets. Without it, you would need to develop custom code to manage the two-way connection and manually bypass client requests.

Next.js

Next.js is a React-based full-stack web development framework that can handle the front and back end. It provides building blocks and tools for building your application’s user interface and server-side systems.

For example, the newer version of Next has a built-in compiler that significantly improves the code refresh time. When developers adjust the application, the changes will reflect in the browser more quickly.

Next.js also employs a pre-rendering mechanism that compiles JavaScript applications instead of the client’s browser on the back end. This helps improve page loading speed and search engine optimization (SEO).

This section will explore several notable websites built on top of Node.js to demonstrate its capabilities.

Netflix

Node.js’ ability to handle real time, I/O-intensive operations makes it an ideal technology for building a live-streaming web application like Netflix.

Uber

Uber utilizes Node.js to handle real time communication between different clients and APIs.

For example, its application processes data from map services, drivers’ global positioning systems, and users’ order requests.

eBay

Node.js enables eCommerce platforms like eBay to efficiently handle API calls from external services like logistics or payment providers.

Moreover, developers can implement such features as inventory management and live chat separately and leverage the runtime’s efficient I/O operations.

PayPal

Payment gateway applications like PayPal work with other APIs and middleware to enable secure, encrypted transactions.

Node.js enables real time data processing from numerous sources, including microservices, for tasks like fraud detection.

Conclusion

Node.js is a runtime environment that lets you run JavaScript code on the server side for back end development. It is built on top of Google’s V8 engine, initially meant for the Chrome web browser.

Node.js employs an asynchronous, non-blocking, event-driven architecture. This runtime uses a single thread to serve multiple concurrent requests without queuing, making it suitable for I/O-intensive applications.

The runtime software, including Node Package Manager (NPM), comes pre-installed on Hostinger Node.js hosting plans. For other providers, you likely need to install it manually using commands or binary packages.

NPM lets you install other frameworks and libraries to complement Node.js, such as React.js and Express.js. These technologies combined are well-suited for enterprise-level applications like PayPal, eBay, and Uber.

What is Node.js FAQ

Is Node.js a programming language or a framework?

Node.js is neither a programming language nor a framework. It is a cross-platform JavaScript runtime environment that enables the scripting language to run as server-side code. 

Can I use Node.js for front end development?

While you can’t directly use Node.js for front end development, it brings additional roles. For example, you can use NPM modules on the front end using tools like Browserify. Several front end libraries like React.js also rely on the runtime environment.

Is Node.js suitable for building scalable web applications?

Absolutely! Node.js allows you to build scalable applications as smaller, isolated components called microservices. It makes your project easier to scale since you can choose particular services to improve without affecting the others.

Author
The author

Aris Sentika

Aris is a Content Writer specializing in Linux and WordPress development. He has a passion for networking, front-end web development, and server administration. By combining his IT and writing experience, Aris creates content that helps people easily understand complex technical topics to start their online journey. Follow him on LinkedIn.