Web Application

What is Node.js? A Quick Guide for Beginners

What is Node.js?

Node js is a javascript server-side framework. It is an open source environment which provides cross-platform accessibility (Windows, Linux, Unix, Mac OS X, etc.). As it is open sourced, it has a huge community and is well maintained by contributers from all over the world. It is built on Google Chrome’s javascript v8 engine which helps applications to run easily with Node.js runtime environment. Various javascript libraries are incorporated in Node.js. With the help of Node js we can easily build web servers as most of the core functionalities are handled by javascript itself. Many compile-to-JS languages are available in which Node.js can be written, for eg. Typescript, Dart etc. With the help of Node js, the whole application can be written in one language that is javascript as it allows you to write both frontend as well as backend.

Brief History of Node.js

Node js was developed by Ryan Dahl in 2009. Initially Node.js was only supported in LINUX and MAC OS. Further Node js was connected with Javascript’s v8 engine. A year later, npm – known as Node.js package manager was introduced in the Node js environment. 

Let us now find out why Node.js is used so widely.

Top Features of Node.js

Here are some of the noteworthy details and features of Node.js. 

1. Node js uses an event-driven, non-blocking I/O

Node js is designed in such a way that the server never waits for API to return data. Instead it moves forward towards execution of other functions. Later whenever the execution gets completed, the notification mechanism notifies the server, hence making it work asynchronously. This makes Node js non-blocking and fast.

const fs = require("fs");
fs.readFile("/file.md", (err, data) => {
   if (err) throw err;
  console.log(data);
});
moreWork(); // will run before console.log

2. Node js application is a single threaded application

Node js is based on a single threaded model with event looping. Due to its asynchronous property and non-blocking way of handling various events by event mechanism, it makes it highly scalable as the server can respond to a higher number of requests though it being single-threaded, unlike traditional servers. 

Node.js application is a single threaded application

3. Node js is highly feasible for real-time data intensive applications

Because of above mentioned features of Node js like asynchronous nature and Google Chrome’s Javascript v8 engine which has very fast execution, its efficiency increases and hence data intensive apps are often developed using Node js. 

4. Node js provides wide range of javascript libraries

Various kinds of libraries available in Node js as javascript modules are quite helpful while development of small-scale to large-scale applications and make the overall process quite simplified.

5. Node js has no data buffering

It follows the process of dividing data into chunks and passing on as output. 

Let’s have a look upon some concepts of Node js to get started with.

Concepts of Node js

Brief idea about some concepts of Node js are as follows:

1. Modules – It is a collection (set) of functions grouped together which can be imported and used in applications. 

2. Event Emitter – Event can also be described as action, so when any action takes place server notifies that the event has taken place.

3. Buffer – Node js can store raw data with raw memory allocation which is outside the v8 heap.

4. Streams – There are 4 types of streams available in Node js namely “Readable, Writable, Duplex and Transform which lets you read and write data.

5. File System – Your file system of the computer can be used directly with Node js to read or write files. You need to import file system module as below: 

var fs = require(“fs”)

6. Callback – As the name suggests, this function is only called whenever any task is completed hence making Node js non-blocking and allowing other functions to run in the meantime. 

7. Promises – These are meant to return the value of the functions later on when all the operations are executed.

8. Error Handling – It refers to the way in which any kind of errors are caught, handled and processed.

Why Node js ?

Here are some points to convince you to use Node js for your next application development.

  • Due to the asynchronous nature of Node js, wait time for functions is eliminated.
  • Works on a callback method notifying whenever any event execution completes.
  • Efficiency increases as it is single threaded and doesn’t occupy much space due to its non-blocking, single threaded nature.
  • The server can directly interact with the file system and perform operations like read, write, delete etc.
  • Can be easily connected with databases and perform data intensive tasks.
  • Can collect a variety of data from api like text, json, objects, arrays, media content as form data.

Event-Driven Approach

Node js though being single-threaded handles non-blocking I/O operations and concurrency with an ease due to event driven approach or event-loop mechanism. 

First let us understand how this event loop actually works:

  • Whenever any request occurs, the event loop checks if whether the stack is empty or are there any ongoing tasks
  • If there are no ongoing tasks then the event loop executes the pending tasks sequentially in first in first out (FIFO) manner using callbacks and promises.
  • When all the tasks are executed successfully, the event loop goes to rest and waits until it receives the next task.

First let us understand how this event loop actually works

  • Whenever any request occurs, the event loop checks if whether the stack is empty or are there any ongoing tasks
  • If there are no ongoing tasks then the event loop executes the pending tasks sequentially in first in first out (FIFO) manner using callbacks and promises.
  • When all the tasks are executed successfully, the event loop goes to rest and waits until it receives the next task.

Phases of event loop in brief

  • Timers: It executes callbacks that are scheduled by setTimeout() or setInterval().
  • Pending callbacks: It executes I/O callbacks that are deferred to the next loop iteration.
  • Idle, prepare: It is only used internally.
  • Poll: It retrieves new I/O events and executes I/O related callbacks.
  • Check: It invokes setIntermediate() callbacks.
  • Close Callbacks: It handles some close callbacks. Eg: socket.on(‘close’, …)

Advantages of Node.js

Since, Node js is so widely used, it has some pros which goes as follows: 

  • Allows you to use javascript as a common base for your application development for frontend and backend.
  • Node js has a huge community worldwide which maintains it quite well.
  • It is open source.
  • Built on a powerful engine that is Google Chrome’s v8 runtime javascript which provides a great runtime environment for Node js.
  • It comes with a powerful ecosystem of a variety of javascript libraries as well as a humongous amount of packages to use in node package manager (npm).
  • Quite efficient and offers high performance in real-time applications.
  • Better speed and performance.
  • Best for microservices due to its lightweight tools.
  • Easy scalability according to modern requirements.
  • Cost effective as it allows javascript to be used as fullstack eliminating the use of other technology.
  • Memory efficient as it is single-threaded.
  • Great choice for building cross-platform applications.
  • It is highly extensible making it available for a variety of different applications.
  • Easy to learn and adapt.

Disadvantages of Node.js

Some of the cons that comes with pros are listed out below:

  • Not suitable for high level intensive computation tasks.
  • Its asynchronous model if not used wisely can be difficult to maintain at code level.
  • Callbacks can turn into callback hell if code complexity and nesting increases.
  • Frequent changes in API can lead to instability.

Applications / non-applications

There are multiple applications in which you can make use of Node.js:

  • Streaming applications
  • Real-time chat applications
  • Data intensive applications
  • I/O based applications
  • Social Media applications
  • Internet of things (IOT)
  • E-commerce applications
  • Single page applications
  • CRM tools
  • API servers
  • Backend for various mobile/web apps

Below is the list of companies that uses Node.js and it will all make sense as why it is so famous: 

  • GoDaddy
  • eBay
  • Paypal
  • NASA
  • Netflix
  • Uber
  • Trello
  • Linkedin
  • MediumWalmart

Where not to use Node.js

Node.js is not really advised to be used on applications with heavy computation. Due to its single-threaded nature all the requests would be blocked hence failing its strongest suit that is event driven non-blocking I/O model. 

Package Manager and Frameworks

1. Node Package Manager (NPM)

Official site: https://www.npmjs.com/

It has 2 functionalities as below:

  1. It provides online repositories for node.js packages/modules which are searchable on search.nodejs.org
  2. It also provides command line utility to install Node.js packages, do version management and dependency management of Node.js packages.

To check npm version, you can open your terminal and enter command

npm –version 

2. Frameworks

Technologies come with different kinds of framework supporting use-cases according to the development required. 

Here are some of the famous Node.js frameworks:

  • Express Js
  • Nest Js
  • Meteor Js
  • Sails Js
  • Hapi Js
  • Feathers Js

Get Started with Node.js

Let’s move on towards some action and setup Node.js in your system

  1. Download Node.js from its official website according to your OS https://nodejs.org/en/download/
  2. To check whether the installation was successful or not, open your terminal and hit the command given below
node –version

And that’s literally it to get started with basic Node.js applications.

Example application

Hello World with a web server

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\n');
});
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Understanding the execution

  • As the first step, the http module is included.
  • http.createServer is a method that creates and returns the server.
  • Constants host and port are specified for the server to run.
  • A callback function is executed and returned to us when the server is up and running.
  • Whenever an event is triggered, it provides a request and response which handle the http call.
  • Now if you head over to http://${hostname}:{port} (http://127.0.0.1:3000) , you will be able to see Hello World displayed on the screen returned as response to the http request.
  • Here statusCode 200 is returned which ensures the successful response to a request.

Conclusion

Overall Node.js can be summarized as an efficient modern day solution which has properties like fast execution, multiple applications and is easy to learn which makes it a popular and reliable environment. Moreover, a vast community along with a number of super amazing frameworks with smooth development processes has attracted many developers and now is foremost amongst the race of server side development languages. 

Apart from that, if you still ponder over why Node.js is a good fit for you from a business perspective, let me tell you in simple words that Node.js provides 3 amazing features that are -> quick delivery, fast pivoting and easily scalable which will work wonders for your next application. 

So when are you trying your hands on Node.js?

Recent Posts

  • OTA

The Rise of Dynamic Packaging in OTA

Using dynamic packaging technology, one can encapsulate flights, accommodation, cars,…

  • UI/Ux Design

Unlocking Digital Success with UX/UI Design

In today’s contemporary era of accelerated digital evolution, the importance…

  • UI/Ux Design

Why UI Design is Important for Your Website? A Step Towards Way Superior UX

The fact is that in today’s internet environment the only…