Introduction to NodeJS
NodeJS is an open-source server-side runtime environment built on Chrome's V8 JavaScript engine. It provides an event-driven, non-blocking (asynchronous) I/O (Input, Output) and cross-platforms runtime environment for building highly scalable server-side applications using JavaScript. NodeJS can be used to build different applications such as command line, web, real-time chat, REST (Representational State Transfer) API server etc.
NodeJS Process Model
Traditional Web Server Model
In the traditional web server model, each request is handled by a dedicated thread from the thread pool. If no thread is available in the thread pool at any point of time then the request waits till the next available thread. Dedicated thread executes a particular request and does not return to the thread pool until it completes the execution and returns a response.
NodeJS Web Server Model
NodeJS processes user requests differently when compares to a traditional web server model. NodeJS runs in a single process and the application code runs in a single thread and thereby needs less resources than other platforms. All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed asynchronously for a particular request. So, this single thread does not have to wait for the request to complete and is free to handle the next request. When asynchronous I/O work completes then to processes the request further and sends the response. An event loop is constantly watching for the events to be raised for an asynchronous job and executing callback function when the job completes. Internally, NodeJS uses libev for the event loop which in turn uses internal C++ thread pool to provide asynchronous I/O.
The following figure illustrates asynchronous web server model using NodejS:
NodeJS Module
Each module in NodeJS has its own context, so it cannot interfere with other modules or pollute the global scope. Also, each module can be placed in a separate
.js
file under a separate folder.NodsJS implements the CommonJS modules standard. CommonJS is a group of volunteers who define JavaScript standards for web server, desktop, and console application.
Types of Modules
Core Modules
NodeJS is a light weight framework. The core modules include bare minimum functionalities of NodeJS. These core modules are compiled into its binary distribution and load automatically when nodeJS process starts. However, you need to import the core module first in order to use it in your application.
HTTP
HTTP module includes classes, methods and events to create NodeJS http server.
URL
URL module includes methods for URL resolution and parsing.
QUERYSTRING
QUERYSTRING module includes methods to deal with Query String.
PATH
Path module includes methods to deal with file paths.
FS
FS module includes classes, methods, and events to work with file I/O.
UTIL
UTIL module includes utility functions useful for programmers.
NPM (Node Package Manager) Basics
NPM is a command line tool that installs, updates or uninstalls NodeJS packages in your application. It is also an online repository for open-source NodeJS packages. The node community around the world creates useful modules and publishes them as packages in this repository.
NPM is included with NodeJS installation.
Using NPM commands
Install package:
npm install -g <package name>
Update package:
npm update <package name>
Uninstall package:
npm uninstall <package name>
Create an empty Node project with NPM:
npm init
or if you want to skip filling out the information's then usenpm init -y
to skip it all.
Official NPM repository website link - npm.
Introduction to ExpressJS
ExpressJS is a web application framework for NodeJS. It provides various features that make web application development faster and easier which otherwise takes more time using only NodeJS.
Advantages of ExpressJS
Makes NodeJS web application development faster and easier.
Easy to configure and customize.
Allows you to define routes of your application based on HTTP methods and URL's.
Includes various middleware modules which you can use to perform additional tasks on request and response.
Easy to integrate with different template engines like Jade, Vash, EJS etc.
Allows you to define an error handling middleware.
Easy to serve static files and resources of your application.
Allows you to create REST API server.
Easy to connect with databases such as MongoDB, Redis, MySQL.
Install ExpressJS
npm i express
Using Express inside NodeJS
NOTE: I will separate each code's but I am working inside the same file.
- exporting express
const express = require('express');
- Creating app object with express
const app = express();
- Creating a local port and listening to the port
// Port might be coming from somewhere else hidden but we will as an example define it here.
const PORT = 4000;
// Listening to the port.
app.listen(PORT, () => {
console.log(`listening on port: ${PORT}`);
});
- Creating a GET request
// app.get => GET request creation.
app.get('/user', (req, res) => {
res.send({
name: 'Aquib',
age: 23,
});
});
- We used
res.send()
but we don't really use them, instead we useres.json()
because it has many functionalities and advantages.
// Data will be coming from database
const user = [
{
name: 'Aquib',
age: 23,
},
{
name: 'User 2',
age: 19,
},
];
app.get('/user', (req, res) => {
res.status(200).json({
success: true,
message: 'users were found',
user,
});
});
For API testing we use tools like Postman or Insomnia, you can download any one of them by clicking on the text.
API and HTTP request types
An API (Application Programming Interface), as the name suggests, is an interface that defines the interaction between different software components. Web API's define what requests can be made to a component (for example, an endpoint to get a list of books), how to make them (for example, a GET request), and their expected responses. There are a few types of HTTP methods that we need to grasp before building REST API. These are the methods that correspond to the CRUD (CREATE, READ, UPDATE and DELETE) tasks:
POST
: Used to submit data, typically used to create new entities or edit already existing entities.GET
: Used to request data from the server, typically used to read data.PUT
: Used to completely replace the resource with the submitted resource, typically used to update data.DELETE
: Used to delete an entity from the server.
As we talked about CRUD operation, CREATE is POST, GET is READ, UPDATE is PUT and DELETE is DELETE.
Understanding the basic concept of how NodeJS works as a server, and how ExpressJS makes our life easier is essential before creating our own API's.
Subscribe to my newsletter
Read articles from Syed Aquib Ali directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Syed Aquib Ali
Syed Aquib Ali
I am a MERN stack developer who has learnt everything yet trying to polish his skills 🥂, I love backend more than frontend.