What is Node.js? An Essential Tool for JavaScript Coders
So why should I learn Node.JS?
JavaScript is starting to dominate the world of programming languages, so if you’re in the world of IT, it’s important to pay attention. More and more companies need to hire JavaScript developers and if you know Node.js well, you’re almost guarantee a good career.
But what is Node.JS is?
In this guide we’ll explore everything from how it works, to its rich features, and its advantages. We’ll also share what you can do with Node.JS and how you can get started with it.
But first, what are some of its benefits? And why is it so popular?
- It’s free to use, accessible, and open source.
- Node.JS is a complete full-stack approach that utilizes a single language (JavaScript).
- Has a ton of practical applications and uses.
- Huge community and support.
- Cross-Platform support.
- There is a huge demand for Node.js in the market.
- Node.JS is a good choice for microservices development.
- A popular and diverse set of tools and frameworks
- Node.JS is speed-oriented and less resource-consuming, making it optimal for real-time applications.
- Relatively low learning curve (Node.JS is not a new programming language. Yet it uses an existing, popular language (JS) to offer better usability).
- It provides scalability to applications.
- It comes with thousands of easy-to-use modules.
- Web apps are just a part of the Node.js ecosystem. You can also use it for native desktop and mobile apps. Often you can do it all using the same codebase.
- Wider industrial recognition and support by multinational companies.
Let’s recap JavaScript again
What is the role of Javascript in web development? JavaScript (JS) is one of the most popular programming languages for web development. Much of the web is built on HTML, CSS, and JS.
JavaScript is well-known as the scripting language for web pages. That’s why you can simply write javascript code in an HTML file and view the output in a browser. It displays and manipulates user interfaces for end-users. JavaScript is a high-level, interpreted, and object-oriented programming language.
First-class functions are one of the special features of JavaScript. It means you can treat functions as variables. Again, that means you can assign functions to other variables. You can also pass functions as arguments to other functions. Let’s see an example here.
Example 1 – Assign function to a variable
const msg = function() { console.log("Hello World"); displayPi() // 3.14159...
//you can call the function using the variable name
msg();
Example 2 – pass function as an argument
function greet() { return "Hello "; } function saySomething(greetWord, name) { console.log(greetWord() + name); } // Pass greet function as an argument to saySomething function saySomething(greet, "Mike");
Do you know that Web browsers have dedicated JavaScript engines? These are used to execute the code on user devices. Some examples are
- Mozilla’s SpiderMonkey is used in Netscape and later in Firefox.
- Google’s V8 is used in Google Chrome and other Chromium-based browsers.
- Microsoft’s Chakra is used in Internet Explorer and the original Edge browser.
From JS to Node.JS
JavaScript engines were developed to be used only in web browsers. Yet, a fantastic turn of events changed the future of JavaScript. In 2009, Ryan Dahl invented the NodeJS project.
NodeJS is an open-source, cross-platform JavaScript runtime environment. It runs on Google’s V8 JavaScript engine (the JavaScript engine used by Chrome).
There is a notable difference between traditional JavaScript and NodeJS. NodeJS executes JavaScript code without the need for a web browser. NodeJS is basically a C++ wrapper built over the V8 engine. It can run as a cross-platform runtime environment without a browser. A runtime environment is a hardware or software environment that executes a code.
Difference between JS and NodeJS
- JavaScript is a programming language that can be used to write JS code. In contrast, Node.JS is not a programming language but a JS runtime environment.
- JavaScript was originally intended to be used on a web browser. The web browser compiles the JS code to machine code. Yet, Node.JS eliminates the need for a web browser to run JavaScript code.
- JavaScript was initially used for front-end web development. It can access and manipulate the DOM. Node.JS doesn’t necessarily do so. It can run both server-side scripting and client-side code.
Exploring NodeJS
Node.js is an open-source, cross-platform runtime environment. It uses event-driven, non-blocking Input/output(I/O) architecture. Non-blocking I/O means it doesn’t wait until IO devices finish their job. Usually, I/O devices take time to perform their operations. But NodeJS lets the system perform the operation and go to the next line of code. This makes Nodejs an excellent choice for developing fast and scalable real-time applications. The following code shows an example of non-blocking(Asynchronous) nature of Nodejs.
The following code opens the file and reads it and prints the content of the file in the console log. It also calculates the total of 1 to 5.
const fs = require('fs'); const filepath = myfile.txt '; fs.readFile(filepath, (err, data) => { console.log(data); }); let total = 0; for (let i = 1; i <= 5; i++) { total = total + i; } console.log(Total: ', total);
In a normal code, the program will read the complete file and print its content first. And then do the for loop and print the total. However, reading files takes time. So in this non-blocking code, you will see the output of the total before writing the content of the file. Because Nodejs don’t wait until file reading operating ends. It goes to the next code to be executed.
What should you know about Node.js Architecture?
Node.js uses the “Single-threaded event loop” architecture. Therefore, when Nodejs receives multiple requests, it puts them in EventQueue. An event loop is an event listener that waits and listens to EventQueue until it hears an event.
How Node.JS works in a real-world application
- It keeps a small number of threads in a limited thread pool. Whenever a request has been made, it will be put in a queue. The single-threaded event loop awaits and picks requests from the queue.
- Then the request is processed and checked to see if it needs an I/O blocking operation. If not, it’ll be processed, and a response will be sent.
- If the request requires I/O blocking, the event loop will assign a thread. This thread is taken from the limited internal pool I said above.
Node.JS is non-blocking. The event loop actively implements this non-blocking nature. It tracks the I/O blocking requests and keeps them in the queue until the I/O blocking task is processed. Thus, the processing of other requests can continue uninterruptedly.
The use of fewer threads results in less resource and memory usage. It will ultimately result in faster execution. It makes Node.JS an ideal choice for building real-time apps.
What are the main features of Node.js
- Easier to get started. It has a minimal setup process and tons of tools, along with a large and supportive community. Moreover, it is easy to access with the availability of useful guides.
- Scalable
- Better performance and speed, with non-blocking threads and less resource usage.
- Cross-platform support with the ability to use the same codebase for multiple OS
- Better reusability and maintainability. Both the server-side and client-side use the same language.
- Third-party libraries/packages. Thousands of third-party open-source packages are accessible via NPM (node package manager).
- Native support for operating systems. Node.JS is written in C/C++ as most OSs are written in C/C++ (Java is also based on C/C++). It adds support for OS-level features like networking.
What is NodeJS used for?
It won’t be easy to answer what Node.JS is used for. It has many practical applications with its capabilities and third-party libraries/packages. Let us discuss some of them.
- Node.js has a native streaming API. It provides lightness, speed, and low resources. Streaming service components use this feature.
- Complex PWA (Progressive Web Applications) and/or SPA (Single Page Applications).
- Applications based on the REST API.
- A proxy-server.
- Application monitoring tools
- Web applications
- Desktop applications (ex: VSCode was built using ElectronJS and NodeJS).
- Massive data collection and processing
- Fintech solutions (ex: PayPal)
- Social networking (ex: LinkedIn)
- IoT solutions.
Getting started with Node.JS
After going through the above facts, you may feel that it’d be overwhelming to learn and start a Node.JS project. However, it’s really not. You are good to go if you have a good grasp of vanilla JavaScript (ECMAScript).
The first step is to install Node.JS on your system. Simply go to www.nodejs.org and download the appropriate installer for your OS.
If you cannot see the correct option, go to Downloads. Then download the correct package and install it.
Once the installation process is over, open up a terminal. This can be Windows CMD, Powershell, or Terminal on Mac. Run the following command and see if the Node.js installation is successful.
node -v
It should output something like the below.
V16.15.1
Building a Simple Web App with Node.JS
After installing Node.JS, we can try creating a simple server app with a message. Open up a new file in your IDE (or any text editor).
My file is named my-app.js in this example. Write the following code there.
In your terminal, go to the directory you’re in, and then run
node my-app.js
You’d see the following as the output.
What is NPM in Node.JS
What is NPM in Node.JS, you might ask? Well, NPM, which stands for Node Package Manager, mainly consists of two things.
- An online repository for thousands of open-source Node.JS packages. Searchable on https://www.npmjs.com/
- A command-line utility for installing and managing versions/dependencies from the above-mentioned packages.
Installing a Package module
NPM will be automatically installed when you’re running Node Installer. It can be used in any of your Node.js projects. NPM is very convenient to use. You can search for the package you want on npmjs. It will provide instructions on installing the package. It’s usually a concise, one-line command that you can simply copy and paste into your terminal.
Then the specified package will be installed in your current directory. You can find it under the .node_modules. After installation, you can use that package in your application.
For example, if you want to use Axios in your application, you can write the following code line.
const axios = require(‘axios’);
Global Install vs. Local Install
Earlier, we simply installed the package module directly into the working directory. So it’s only accessible on that particular project. There is another method for installing the package module globally. It will allow us to use that package module in any application we build.
As in the previous method, we can use npm install to accomplish this global installation. Yet, we have to pass an additional parameter ( -g ).
npm install coffee-script -g
This command will install the package on your system and create a symlink to make it available. As per the above example, running coffee in any directory would now be possible. You will also have access to the CoffeeScript REPL anywhere in your system.
Dependency Management with NPM
When you get a Node project developed by someone else, you’ll get it with a file named package.json. It’ll contain information on all the node modules used by the project. You can run npm install inside the project root to install all the node modules required for the project.
This approach will make it much easier to distribute or clone from a repo. You’ll get only the important project files directly. Then you can install all the dependencies separately (or choose what to install).
And you’re done!