0% found this document useful (0 votes)
7 views

Introduction to Node

Node.js is an open-source JavaScript runtime that allows for asynchronous, non-blocking operations, making it efficient for handling multiple connections. It utilizes npm as its package manager, which supports a vast ecosystem of libraries and tools for development. The document also discusses various Node.js frameworks, highlighting their features and use cases, particularly for real-time applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Introduction to Node

Node.js is an open-source JavaScript runtime that allows for asynchronous, non-blocking operations, making it efficient for handling multiple connections. It utilizes npm as its package manager, which supports a vast ecosystem of libraries and tools for development. The document also discusses various Node.js frameworks, highlighting their features and use cases, particularly for real-time applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Introduction to Node.

js

Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular


tool for almost any kind of project!

Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser.
This allows Node.js to be very performant.

A Node.js app runs in a single process, without creating a new thread for every request.
Node.js provides a set of asynchronous I/O primitives in its standard library that prevent
JavaScript code from blocking and generally, libraries in Node.js are written using non-
blocking paradigms, making blocking behavior the exception rather than the norm.

When Node.js performs an I/O operation, like reading from the network, accessing a
database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting,
Node.js will resume the operations when the response comes back.

This allows Node.js to handle thousands of concurrent connections with a single server
without introducing the burden of managing thread concurrency, which could be a
significant source of bugs.

Node.js has a unique advantage because millions of frontend developers that write
JavaScript for the browser are now able to write the server-side code in addition to the
client-side code without the need to learn a completely different language.

In Node.js the new ECMAScript standards can be used without problems, as you don't have
to wait for all your users to update their browsers - you are in charge of deciding which
ECMAScript version to use by changing the Node.js version, and you can also enable specific
experimental features by running Node.js with flags.

An introduction to the npm package manager

Introduction to npm

npm is the standard package manager for Node.js.

In September 2022 over 2.1 million packages were reported being listed in the npm registry,
making it the biggest single language code repository on Earth, and you can be sure there is
a package for (almost!) everything.

It started as a way to download and manage dependencies of Node.js packages, but it has
since become a tool used also in frontend JavaScript.

Yarn and pnpm are alternatives to npm cli. You can check them out as well.

Packages
npm installs, updates and manages downloads of dependencies of your project.
Dependencies are pre-built pieces of code, such as libraries and packages, that your Node.js
application needs to work.

Installing all dependencies

If a project has a package.json file, by running

npm install

ShellCopy to clipboard

it will install everything the project needs, in the node_modules folder, creating it if it's not
existing already.

Installing a single package

You can also install a specific package by running

npm install <package-name>

ShellCopy to clipboard

Furthermore, since npm 5, this command adds <package-name> to


the package.json file dependencies. Before version 5, you needed to add the flag --save.

Often you'll see more flags added to this command:

 --save-dev installs and adds the entry to the package.json file devDependencies

 --no-save installs but does not add the entry to the package.json file dependencies

 --save-optional installs and adds the entry to


the package.json file optionalDependencies

 --no-optional will prevent optional dependencies from being installed

Shorthands of the flags can also be used:

 -S: --save

 -D: --save-dev

 -O: --save-optional

The difference between devDependencies and dependencies is that the former contains
development tools, like a testing library, while the latter is bundled with the app in
production.

As for the optionalDependencies the difference is that build failure of the dependency will
not cause installation to fail. But it is your program's responsibility to handle the lack of the
dependency. Read more about optional dependencies.
Updating packages

Updating is also made easy, by running

npm update

ShellCopy to clipboard

npm will check all packages for a newer version that satisfies your versioning constraints.

You can specify a single package to update as well:

npm update <package-name>

ShellCopy to clipboard

Versioning

In addition to plain downloads, npm also manages versioning, so you can specify any specific
version of a package, or require a version higher or lower than what you need.

Many times you'll find that a library is only compatible with a major release of another
library.

Or a bug in the latest release of a lib, still unfixed, is causing an issue.

Specifying an explicit version of a library also helps to keep everyone on the same exact
version of a package, so that the whole team runs the same version until
the package.json file is updated.

In all those cases, versioning helps a lot, and npm follows the semantic versioning (semver)
standard.

You can install a specific version of a package, by running

npm install <package-name>@<version>

ShellCopy to clipboard

Running Tasks

The package.json file supports a format for specifying command line tasks that can be run by
using

npm run <task-name>

ShellCopy to clipboard

For example:

{ "scripts": { "start-dev": "node lib/server-development", "start": "node lib/server-


production" }}
JSONCopy to clipboard

It's very common to use this feature to run Webpack:

{ "scripts": { "watch": "webpack --watch --progress --colors --config webpack.conf.js",


"dev": "webpack --progress --colors --config webpack.conf.js", "prod":
"NODE_ENV=production webpack -p --config webpack.conf.js" }}

JSONCopy to clipboard

So instead of typing those long commands, which are easy to forget or mistype, you can run

$ npm run watch$ npm run dev$ npm run prod

The Node.js Event emitter

If you worked with JavaScript in the browser, you know how much of the interaction of the
user is handled through events: mouse clicks, keyboard button presses, reacting to mouse
movements, and so on.

On the backend side, Node.js offers us the option to build a similar system using
the events module.

This module, in particular, offers the EventEmitter class, which we'll use to handle our
events.

You initialize that using

CJSMJS

const EventEmitter = require('node:events');const eventEmitter = new EventEmitter();

JavaScriptCopy to clipboard

This object exposes, among many others, the on and emit methods.

 emit is used to trigger an event

 on is used to add a callback function that's going to be executed when the event is
triggered

For example, let's create a start event, and as a matter of providing a sample, we react to
that by just logging to the console:

eventEmitter.on('start', () => { console.log('started');});

JavaScriptCopy to clipboard

When we run

eventEmitter.emit('start');

JavaScriptCopy to clipboard
the event handler function is triggered, and we get the console log.

You can pass arguments to the event handler by passing them as additional arguments
to emit():

eventEmitter.on('start', number => { console.log(`started $


{number}`);});eventEmitter.emit('start', 23);

JavaScriptCopy to clipboard

Multiple arguments:

eventEmitter.on('start', (start, end) => { console.log(`started from ${start} to $


{end}`);});eventEmitter.emit('start', 1, 100);

JavaScriptCopy to clipboard

The EventEmitter object also exposes several other methods to interact with events, like

 once(): add a one-time listener

 removeListener() / off(): remove an event listener from an event

 removeAllListeners(): remove all listeners for an event

NodeJS is a JavaScript runtime environment for running JavaScript applications outside the
browser environment. It’s asynchronous and event-driven, meaning it doesn't block the
event loop - making NodeJS highly suitable for the development of server-side web
applications.

With around 50,000 open source packages available through npm (Node Package Manager),
NodeJS facilitates the seamless backend extension. The GitHub repository has 99k stars and
27.5k forks demonstrating an active community. Furthermore, there are 468,194 questions
tagged 'node.js' on Stackoverflow, while an active Discord community comprises 13,714
members.

Due to its popularity, there are now hundreds of NodeJS frameworks but some outperform
others when it comes to their performance, community support, and ease of use. In this
article, we’ll explore the top NodeJS frameworks including those that enable you to add
realtime features to Node applications. We will also look at some tips to help you choose the
best framework for your app.

What are NodeJS frameworks?

NodeJS frameworks are a set of libraries, templates, and tools built on top of the Node
environment. These frameworks offer a basic structure for applications including routes,
middleware, and templates that streamline the development process. As discussed above, a
significant number of NodeJS frameworks are available, each with its own unique features,
strengths, and weaknesses.

Realtime frameworks in NodeJS simplify the development of a crucial aspect of modern web
development, encompassing realtime features such as chat, notifications, data streaming,
and more. Amongst the numerous realtime NodeJS frameworks available, there are a few
notable ones including Socket.IO, Feathers.js, Meteor.js, and Sails, which we will explore in
this article.

Why use NodeJS frameworks?

NodeJS frameworks provide syntactic sugar (easier syntax), simplifying the development
process with added functionality.

To understand the syntactic sugar, have a look at the code snippet below that showcases the
displaying of a <h2> tag on the home route using NodeJS and Express framework
respectively. Note that in NodeJS, we create an ‘http’ server, use ‘setHeader’ to manually set
the response content type and write all the required HTML tags to be able to display the
<h2> tag. On the other hand, in Express, we only need to create an Express application and
send the <h2> tag as a response on the home route:

//NodeJS

const server = http.createServer((req, res) => {

res.setHeader('Content-Type', 'text/html');

res.write('<html>');

res.write('<head><title>Best NodeJS Frameworks</title><head>');

res.write('<body><h2>Hello from the Ably Blog</h2></body>');

res.write('</html>');

res.end();

});

// Express

const express = require('express');

const app = express();

app.get('/', (req, res) => {


res.send('<h2>Hello from the Ably Blog</h2>');

});

7 Best NodeJS Frameworks

General purpose NodeJS frameworks

1. Express

Express is the most popular and minimalistic web framework for NodeJS. Express is designed
to simplify the backend application development with a robust set of features including
routing, middleware, error handling, and templating.

Key features:

 Minimal and easy to use: Express makes the development process easy and fast with
its set of core features. Built on top of JavaScript, it's easy to learn, and includes
several NodeJS features as functions like routing and middleware.

 Middleware integration: Express allows developers to include important


functionalities with the help of middleware in their projects.

 MVC architecture: Express has MVC architecture which allows dividing a larger
complex application into smaller parts making it easier to understand and navigate.

Community stats:
The official Express GitHub repository has 62.1k stars and 11.7k forks. The Express mailing
list has over 5000 discussions which can be used as an issue library when you encounter a
bug while developing an Express application.

Use cases and applications:


Building APIs, backend mobile and web servers, realtime applications, are use cases for
Express. Companies using Express include:

 X (Twitter): Twitter uses Express to build its API.

 Accenture: Accenture uses Express to build its API and share data among
stakeholders.

 Trustpilot: Trustpilot uses Express to build its application and API.

2. Fastify

Fastify is a lightweight web framework for NodeJS built on top of Express. It emphasizes low
overhead and responsive user experience.

Key features:

 Lightweight: Fastify is a light framework which ensures better functionality with low
overhead.
 Schema based: Fastify recommends using JSON schema for the validation and
serialization of routes.

 Easy to use: Fastify has a straightforward API which makes it easy to learn and use for
production-ready projects.

Community stats:
Fastify has a community of 28.8k stars and 2.2k forks on GitHub.

Use cases and applications:


Fastify can be used to build fast and scalable server-side applications. Companies using
Fastify include:

 Compressor: Compressor uses Fastify for the development of fast applications.

 Joggr: Joggr uses Fastify for a fast and low-overhead responsive application.

Is Fastify better than Express?

There is an ongoing discussion among developers regarding whether Fastify is better than
Express. Both Fastify and Express are NodeJS frameworks with similar functionalities.
However, Fastify performs faster than Express, while Express provides more robust routing
and is preferred by most developers. The choice of a framework depends on your
requirements. You can check out this discussion on Reddit where developers share their
viewpoints on this dilemma. We will talk about considerations while picking a NodeJS
framework later in the article.

3. NestJS

NestJS is a progressive framework for NodeJS for building server-side applications with
JavaScript and TypeScript. NestJS follows a modular architecture enabling developers to
create complex applications by organizing components into separate, independent modules,
ensuring maintainability and reusability across various parts of the application.

Key features:

 Modular architecture: NestJS offers a modular architecture which allows isolating


parts and layers of an application for increased maintainability and scalability.

 TypeScript support: NestJS supports TypeScript while allowing developers to code in


JavaScript.

 CLI tool: The Nest CLI allows easier setup and development of applications through
simple commands.

Community stats:
NestJS has a large community with 60.5k stars and 7.2k forks on GitHub. 12,033 are tagged
'nestjs' on StackOverflow and an active discord community of 43,436 is also there to support
fellow developers.
Use cases and applications:
Like other NodeJS frameworks, NestJS can be used to develop server-side applications.
Companies using NestJS include Adidas and graph data platform, Neo4j.

Realtime NodeJS frameworks

Realtime frameworks provide features and functions to enable simplified development of


realtime applications. Realtime applications require realtime flow of information, like with
instant messaging or for data analytics dashboards.

Here are some of the best realtime NodeJS frameworks to consider.

4. Socket.IO

Socket.IO is a NodeJS framework built on top of WebSockets that enables realtime client-
server communication. Socket.IO is event-driven and compatible with older browsers and
environments.

Key features:

 Automatic reconnection: Socket.IO automatically reconnects if a connection


between the client and server is interrupted.

 Old browser support: Socket.IO offers a fallback HTTP long-polling mechanism


allowing it to work on older browsers as well.

 Packet buffering: In the event of a disconnection, Socket.IO buffers packets which are
sent to the client upon reconnection, ensuring that no data is lost.

Community stats:
Socket.IO has a community with 59.2k stars and 10.2k forks on GitHub.

Use cases and applications:


Chat applications, realtime multiplayer games, social media apps, and realtime dashboards
are some of the use cases of Socket.IO. Companies using Socket.IO include:

 Slack: Slack uses Socket.IO to enable realtime communication between users.

 Twitter: Twitter uses Socket.IO to enable realtime updates to user feeds,


notifications, and search results.

Read more about Socket.IO and when to use it.

5. Feathers.js

Feathers.js is a web framework built on top of Express which provides a simple way to
develop a scalable and reliable application. Feathers.js supports many databases and works
with any frontend technology including iOS, Android, and React Native.

Key features:
 Microservices architecture: Feathers.js offers a microservices architecture which
allows dividing an application into smaller independent services that can be deployed
separately.

 Realtime Support: Feathers.js uses Socket.IO enabling the development of realtime


applications.

Community stats:
Feathers.js has a small but active community with 14.8k stars and 761 forks on GitHub.

Use cases and applications:


Feathers.js can be used for building realtime applications and APIs. Chatbot Plus uses
Feather.js for the integration of realtime features in their application.

6. Meteor.js

Meteor.js is a fullstack NodeJS framework built specifically for JavaScript which allows easy
development of realtime features with its straightforward API.

Key features:

 Remote Procedure Call (RPC) system: Meteor.js allows easy frontend and backend
integration with its RPC API methods.

 Built-in accounts: Ready to use login and account package not requiring developers
to build their own authentication system.

 Pub/Sub method: Easy development of realtime features using publications and


subscriptions.

Community stats:
The Meteor.js GitHub repository has an active community with 43.8k stars and 5.4k forks.

Use cases and applications:


Meteor.js allows building applications for browsers, web, and application servers including
realtime features such as chat and data updates. Companies using Meteor.js include:

 Azumuta: Azumuta application is developed using Meteor.js along with other


technologies.

 Forage: The Forage website is developed using Meteor.js.

7. Sails:

Sails is a realtime MVC framework for NodeJS built on top of Express. Sails has a flexible
routing system and comes with built-in realtime communication support.

Key features:
 ORM (Object Relational Mapping): Sails provides a simple data access layer allowing
data access from any database.

 Auto-generate REST APIs: Sails provides blueprints for REST APIs which can be
generated using a simple `sails generate api dentist` command.

 WebSockets support with no additional code: Sails allows realtime feature


development using WebSockets without having to write additional code.

Community stats:
Sails GitHub repository has an active community with 22.78k stars and 2k forks. They also
have a YouTube channel with a library of useful tutorial videos.

Use cases and applications:


Sails is suitable for building realtime chat applications, APIs, fullstack mobile or web
applications. Sails is a relatively new framework with limited information on what companies
are using it. However, according to some online sources the following companies use Sails:

 Anybot: A platform to create custom AI bots.

 The Canero Group: A real estate brokerage and development company.

How to choose the Best NodeJS framework

Choosing the best NodeJS framework depends on the project needs and scope, and
company requirements. A few considerations you can make while shortlisting the NodeJS
frameworks are:

Project requirements

Understand your project requirements such as the realtime features, scalability, and
complexity. For example, you might consider using Express for backend server with Socket.IO
to enable realtime communication. This combination will allow you to develop a robust and
scalable application however, some developers might find it difficult and prefer using one
framework that allows developing both an API and realtime features like Sails, Meteor.js, or
Feathers.js. Applications that only need a backend server without realtime functionalities
can be built in other frameworks like Express or Fastify.

Community support and documentation

A framework that has an active community can help you in many ways. An active community
indicates a well-maintained and continuously improved framework. Community can become
your support if you encounter issues while developing your application asking them for
tested tips and tricks. An active and large community also means you can find a larger
number of resources, tutorials, and guides for a framework as compared to others. For
example, Express and NestJS have larger active communities compared to Meteor.js with
only 280 discord members and a deactivated Slack channel.
Common limitations

Each framework comes with its own limitations. It's essential to consider those limitations
and tradeoffs you might have to make while considering different frameworks. For example,
Socket.IO offers a fallback mechanism for environments where WebSockets are not
supported while Sails only comes with the option of WebSockets for realtime features.

Conclusion

Throughout this article, we explored some of the widely used NodeJS frameworks including
Express, NestJS, Fastify, Socket.IO, Feathers.js, Meteor.js, and Sails including their key
features and the companies that are leveraging their capabilities. We also discussed
tradeoffs that you might have to make while choosing frameworks and the tips to pick the
best framework for your needs.

We'd love to hear about your experiences and see the innovative projects you are building
using NodeJS - share your projects with us on X (Twitter) or Reddit.

You might also like