JavaScript is one of the most popular programming languages in the world. It powers millions of websites today, and it has attracted droves of developers and designers to build features for the web. If you’re new to programming, JavaScript is easily one of the best programming languages to get under your belt.
For its first 20 years, JavaScript was used mainly for client-side scripting. Since JavaScript could be used only within the <script>
tag, developers had to work in multiple languages and frameworks between the front-end and back-end components. Later came Node.js, which is a run-time environment that includes everything required to execute a program written in JavaScript.
Node.js is a single-threaded, open-source, cross-platform runtime environment for building fast and scalable server-side and networking applications. It runs on the V8 JavaScript runtime engine, and it uses event-driven, non-blocking I/O architecture, which makes it efficient and suitable for real-time applications.
What Is Node.js Written In?
Node.js is written in C, C++, and JavaScript.
Wikipedia defines Node.js as “a packaged compilation of Google’s V8 JavaScript engine, the libuv platform abstraction layer, and a core library, which is itself primarily written in JavaScript.”
The runtime uses Chrome V8 internally, which is the JavaScript execution engine, and it’s also written in C++. This adds additional use cases to Node.js’s repertoire, such as accessing internal system functionality (like networking).
Node.js Architecture and How It Works
Node.js uses the “Single Threaded Event Loop” architecture to handle multiple clients at the same time. To understand how this is different from other runtimes, we need to understand how multi-threaded concurrent clients are handled in languages like Java.
In a multi-threaded request-response model, multiple clients send a request, and the server processes each one before sending the response back. However, multiple threads are used to process concurrent calls. These threads are defined in a thread pool, and each time a request comes in, an individual thread is assigned to handle it.
Node.js works differently. Let’s take a look at each step it goes through:
- Node.js maintains a limited thread pool to serve requests.
- Whenever a request comes, Node.js places it into a queue.
- Now, the single-threaded “Event loop”—the core component—comes into the picture. This event loop waits for requests indefinitely.
- When a request comes in, the loop picks it up from the queue and checks whether it requires a blocking input/output (I/O) operation. If not, it processes the request and sends a response.
- If the request has a blocking operation to perform, the event loop assigns a thread from the internal thread pool to process the request. There are limited internal threads available. This group of auxiliary threads is called the worker group.
- The event loop tracks blocking requests and places them in the queue once the blocking task is processed. This is how it maintains its non-blocking nature.
Since Node.js uses fewer threads, it utilizes fewer resources/memory, resulting in faster task execution. So for our purposes, this single-threaded architecture is equivalent to multi-threaded architecture. When one needs to process data-intensive tasks, then using multi-threaded languages like Java makes much more sense. But for real-time applications, Node.js is the obvious choice.
Features Of Node.js
Node.js has grown quickly in the last few years. This is thanks to the vast list of features it provides:
- Easy—Node.js is quite easy to start with. It’s a go-to choice for web development beginners. With a lot of tutorials and a large community—getting started is very easy.
- Scalable—It provides vast scalability for applications. Node.js, being single-threaded, is capable of handling a huge number of simultaneous connections with high throughput.
- Speed—Non-blocking thread execution makes Node.js even faster and more efficient.
- Packages—A vast set of open-source Node.js packages is available that can simplify your work. There are more than one million packages in the NPM ecosystem today.
- Strong backend—Node.js is written in C and C++, which makes it speedy and adds features like networking support.
- Multi-platform—Cross-platform support allows you to create SaaS websites, desktop apps, and even mobile apps, all using Node.js.
- Maintainable—Node.js is an easy choice for developers since both the frontend and backend can be managed with JavaScript as a single language.
Market Size
There has been immense growth in websites in the last 2 decades, and as expected, Node.js is growing fast as well. The popular runtime already crossed the 1-billion download threshold back in 2018, and according to W3Techs, Node.js is used by 1.2% of all websites everywhere. That’s over 20 million total sites across the internet.
Not surprisingly, it’s a popular selection with millions of companies, too. Here are a few popular ones that use Node.js today:
- Spotify
- eBay
- Godaddy
Applications Of Node.js
Node.js is used for a wide variety of applications. Let’s explore some popular use cases where Node.js is a good choice:
- Real-time chats—Due to its single-threaded asynchronous nature, Node.js is well-suited to processing real-time communication. It can easily scale and is often used in building chatbots. Node.js also makes it simple to build additional chat features like multi-person chat and push notifications.
- Internet of Things—IoT applications usually comprise multiple sensors, as they frequently send small chunks of data that can pile into a large number of requests. Node.js is a good choice since it’s able to handle these concurrent requests quickly.
- Data streaming—Companies like Netflix use Node.js for streaming purposes. This is mainly due to Node.js being lightweight and fast, besides which Node.js provides a native streaming API. These streams allow users to pipe requests to each other, resulting in data being streamed directly to its final destination.
- Complex single-page applications (SPAs)—In SPAs, the whole application is loaded in a single page. This usually means there are a couple of requests made in the background for specific components. Node.js’s event loop comes to the rescue here, as it processes requests in a non-blocking fashion.
- REST API-based applications—JavaScript is used both in the frontend and backend of sites. Thus, a server can easily communicate with the frontend via REST APIs using Node.js. Node.js also provides packages like Express.js and Koa that make it even easier to build web applications.
Is Node.js A Programming Language?
In a word: no.
Node.js is not a programming language. Rather, it’s a runtime environment that’s used to run JavaScript outside the browser.
Neither is Node.js a framework (a platform for developing software applications). The Node.js runtime is built on top of a programming language—in this case, JavaScript—and helps in running frameworks itself.
To sum up, Node.js is neither a programming language nor a framework; it’s an environment for them.
Is Node.js Frontend Or Backend?
A common misconception among developers is that Node.js is a backend framework and is only used for building servers. This isn’t true: Node.js can be used both on the frontend and the backend.
One of the reasons Node.js frameworks are a popular choice for developers building a flexible and scalable backend is its event-driven, non-blocking nature. However, frontend developers will see these benefits of Node.js in their own work just as clearly.
Let’s take a look at why Node.js works for both backend and frontend:
- Reusability – JavaScript is a common language that’s used to write both backend and frontend with the help of frameworks like Express.js and Meteor.js. Some popular stacks like MERN use Express.js as a backend (a Node.js framework). Multiple components can be reused between frontend and backend as well.
- Productivity and developer efficiency – Thanks to a reduction in context-switching between multiple languages, a great deal of developer time can be saved. Using JavaScript for both backend and frontend results in increased efficiency, as many tools are common for both.
- Huge community – A thriving online community factors into the speed of a successful development cycle. When you get stuck on a problem, there’s a good chance that someone’s already solved it and shared the solution on Stack Overflow. Node.js makes great use of this community, which is active and engaged when it comes to the popular runtime and its packages.
Getting Started With Node.js
It can be overwhelming to decide where to start with Node.js. Fortunately, it’s simple enough to install, and then you’ll be able to test-drive it for yourself.
How To Install Node.js
If you already have Node.js installed, feel free to move past this section.
On macOS
Using Bash on Mac
curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg.*|\1|p')}.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/"
Using Homebrew on Mac
brew install node
On Windows
Download the Windows Installer directly from the nodejs.org website.
On Linux
On Ubuntu 18.04+ you can install Node using the following commands.
sudo apt update
sudo apt install nodejs
Check The Version Of Node.js Installed
In the previous section, we successfully installed Node. Let’s verify it by checking the installed version. Run the following command in the terminal.
node -v
You can also check it via the longer flag
node --version
You should see an output similar to this. Though the version number might vary.
v14.16.0
What Is NPM?
NPM is Node.js’s package ecosystem. It is the largest ecosystem of all open-source libraries in the world, with over 1 million packages and growing. NPM is free to use, and thousands of open source developers contribute to it daily.
NPM comes with a command-line utility out-of-box. You can simply head over to the NPM website to search for the package you need, and install it using a single command. You can also manage your package’s versions, review dependencies, and even set up custom scripts in your projects through this command-line utility. Without a doubt, NPM is the most-loved possession of the Node.js community; Node.js attracts a large number of developers due largely to its excellent package support.
Installing NPM Packages Via CLI
When you install Node.js, NPM is automatically installed along with it. We covered how to install Node.js in the previous sections, so now let’s take a look at the command for installing a package with NPM:
npm install <package-name>
Yes, it’s that easy! You can even install multiple packages at once:
npm install <pkg-1> <pkg-2> <pkg-3>
You can also specify the -g (global) flag if you want to install a package in the global context. This allows you to use the package anywhere across your machine.
When you initialize a new application, NPM automatically creates a package.json file that consists of all the NPM packages. It’s here you can specify versions, dependencies, and custom scripts.
There’s a long list of commands that come with the NPM utility, including publish
, audit
, run
, and more. You can check how to use these using the npm help
command.
Popular Packages
Here are some of the most popular packages for Node.js today:
- Express – Express.js, or simply Express, is a Sinatra-inspired web development framework for Node.js, and the de-facto standard for the majority of Node.js applications out there today.
- MongoDB – The official driver to MongoDB. It provides the API for MongoDB object databases in Node.js.
- Socket.io – Socket enables real-time, bidirectional, and event-based communication.
- Lodash – Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc.
- Moment – A JavaScript date library for parsing, validating, manipulating, and formatting dates.
- Commander.js – This is all you need to work and build with command-line interfaces for node.js.
- Forever – A simple CLI tool for ensuring that a given script runs continuously (i.e. forever). Keeps your Node.js process up in production in the face of any unexpected failures.
- Async – A utility module that provides straightforward, powerful functions for working with asynchronous JavaScript.
- Redis – A client library for supporting Redis database integration.
- Mocha – A clean, flexible JavaScript test framework for Node.js and the browser.
- Passport – Simple, unobtrusive authentication for Node.js. Passport’s sole purpose is to authenticate requests.
Hello World In Node.js
As always, let’s start with the basic “Hello World” program, where we create a server in Node.js that will be returning a “Hello World” output on a server request. Before you dive in, be sure to set yourself up with a good text editor.
Once you’ve opened your text editor, here’s the code you’ll use for your “Hello World” program:
// server.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World! Welcome to Node.js');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Save this file as `server.js`. Now head over to the terminal and start the server using the command:
node server.js
The server should start running now. To verify the output, open http://localhost:3000 in your browser. You should see the message –
Hello World! Welcome to Node.js
Explanation Of Hello World Server
Node.js comes with a built-in module called “HTTP” which allows Node.js to transfer data over the HyperText Transfer Protocol (HTTP).
In the code above, we first load the http module in our program. Then we use the createServer method to accept a request and return a response with a status code. Finally, we listen at a defined port.
Congrats—you just created your first server in Node.js! In the next section, we’ll learn how to use the Express framework to create a server.
Creating Server Using Express
Firstly, we should discuss what a server is. A server is responsible for taking client requests through its software (most commonly Apache or Nginx), performing the required set of tasks, and finally sending responses back to the clients. Express is a framework that will help us create a server in Node.
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It allows adding route tables and setting up middleware in your application. You can install Express using the command below.
npm install express --save
In the previous section, we used the in-built http utility to create a server. Now, let’s create a “Hello World” server using Express.js.
Open your text editor and enter this code:
// server-express.js
const express = require('express')
const app = express() // initialize app
const port = 3000
// GET callback function returns a response message
app.get('/', (req, res) => {
res.send('Hello World! Welcome to Node.js')
})
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`)
})
Next, we’ll run our server with the following command.
node server-express.js
Now check http://localhost:3000 in your browser to see the “Hello World” output.
Summary
In a nutshell, Node.js is a popular programming environment that can be used for building high-scale applications that need to support multiple concurrent requests. Single-threaded non-blocking I/O makes it an excellent choice for both real-time and data streaming applications, too.
To beef it up, even more, Node.js has a massive community of active developers and boasts the world’s largest open-source package repository, NPM, which presently contains over a million packages.
It’s easy to get started with Node.js. We’ve covered how to install and create a server in Node.js, so all that’s left is to consider how you’ll use and implement Node.js in your own stack. You can also expand your knowledge by visiting the official Node.js documentation at nodejs.dev.