0% found this document useful (0 votes)
34 views36 pages

Node Js Essentials Mastering Backend

Node.js is a powerful, open-source JavaScript runtime environment that allows developers to execute JavaScript on the server side, enhancing web development capabilities. It features an asynchronous event-driven architecture, a unified language for full-stack development, and a massive ecosystem of libraries through npm. The document also outlines the history, key principles, and popular built-in modules of Node.js, emphasizing its efficiency and scalability in handling web applications.

Uploaded by

chaitanya.kp15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views36 pages

Node Js Essentials Mastering Backend

Node.js is a powerful, open-source JavaScript runtime environment that allows developers to execute JavaScript on the server side, enhancing web development capabilities. It features an asynchronous event-driven architecture, a unified language for full-stack development, and a massive ecosystem of libraries through npm. The document also outlines the history, key principles, and popular built-in modules of Node.js, emphasizing its efficiency and scalability in handling web applications.

Uploaded by

chaitanya.kp15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Node.

js Essentials - Mastering Backend

Node.js has emerged as one of the most in uential and revolutionary technologies in web

development. It is a powerful JavaScript runtime environment that has gained immense

popularity among developers in recent years. In this article, we will explore what Node.js is,

why it has become a preferred choice for web development, and its fascinating history.

What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment allowing

developers to execute JavaScript code outside a web browser. Unlike traditional JavaScript,

which runs primarily on the client side, Node.js enables the execution of JavaScript on the

server side. This means that developers can now use JavaScript to build server-side

applications, which was previously limited to other programming languages like Python or

PHP.

At the core of Node.js lies the V8 JavaScript engine developed by Google, which compiles

JavaScript code directly into machine code for e cient and lightning-fast execution. The V8

engine has played a crucial role in making Node.js a high-performance platform for building

scalable web applications.

Why Use Node.js?

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

1. Asynchronous Event-Driven Architecture: Node.js follows an event-driven

architecture, making it ideal for handling asynchronous operations. This approach

allows Node.js to e ciently manage a large number of concurrent connections without

the need for additional threads, leading to improved scalability and resource e ciency.

2. Fast and Lightweight: Node.js is renowned for its speed and lightweight nature. It

executes code swiftly by leveraging the V8 engine and o ers a non-blocking I/O model,

making it a perfect choice for real-time applications like chat applications or online

gaming.

3. Uni ed Language: With Node.js, developers can use JavaScript for both client-side

and server-side development, promoting code reuse and enhancing developer

productivity. This uni ed language approach has led to the rise of full-stack JavaScript

development.

4. Massive Ecosystem (npm): Node.js boasts a vast and robust ecosystem of open-

source libraries and packages made available through the Node Package Manager

(npm). This extensive collection of modules simpli es the development process,

allowing developers to focus on building innovative features rather than reinventing the

wheel.

5. Community and Support: Node.js has an active and vibrant community of

developers worldwide. The community actively contributes to the platform by sharing

knowledge, creating new packages, and supporting fellow developers.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

History of Node.js
The story of Node.js dates back to 2009 when Ryan Dahl, a developer, introduced this

groundbreaking technology. Dissatis ed with the limitations of traditional web servers and

seeking a more e cient approach to handling I/O operations, Dahl conceived the idea of a

server-side JavaScript runtime. He aimed to create a non-blocking, event-driven architecture

to enable asynchronous I/O.

Key milestones in the history of Node.js include:

1. Prototype Development (2009):


In May 2009, Ryan Dahl released the rst version of Node.js to the public. The initial release

was an experimental implementation of the event loop, showcasing the concept of

asynchronous I/O with JavaScript. The prototype garnered attention within the developer

community, and Node.js began to gain traction.

2. Stable Release (2010):


After extensive development and improvements, Node.js reached its rst stable version

(0.1.14) in March 2010. With the introduction of npm, Node Package Manager, developers

gained access to an extensive repository of packages, signi cantly enhancing the capabilities

of Node.js.

3. Growing Popularity (2011-2013):


Node.js rapidly gained popularity due to its unique features and advantages. Large

companies like LinkedIn and Yahoo adopted Node.js for their applications, boosting their

reputation and adoption rate.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

4. Formation of the Node.js Foundation (2015):


To ensure Node.js's sustainable growth and development of Node.js, key contributors and

stakeholders created the Node.js Foundation in 2015. The foundation aimed to oversee

governance, collaboration, and resource allocation for Node.js projects.

5. Node.js and the Enterprise (2016-present):


Node.js found its way into the enterprise world, where it is now extensively used to build

scalable and high-performance applications. Its use cases range from building real-time chat

applications to microservices architecture.

6. Node.js Community and Continued Development:


The Node.js community remains highly active, continuously improving the platform,

expanding its ecosystem, and providing valuable feedback. New features and

enhancements are regularly added, making Node.js an ever-evolving technology.

“Node.js goal is to provide an easy way to build scalable network programs” → Ryan Dahl,

creator of Node.js.

Understanding the Node environment is crucial to building scalable systems with it. The rst

principle to remember is that the Node.js engine chooses clarity and simplicity over

complexity and unpredictable codes.

Therefore, here’s a simple summary of the Node.js environment.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

There is one thread bound to an event loop.

Deferred tasks are encapsulated, entering and exiting the execution context via

callbacks.

I/O operations generate event data streams that are piped through a single stack.

Concurrency is managed by the system, abstracting away thread pools and simplifying

memory management.

Dependencies and libraries are introduced through a package management system,

neatly encapsulated and easy to distribute, install and invoke.

What problems are Node.js Solving?


1. How to serve many thousands of simultaneous clients e ciently

2. Scaling networked applications beyond a single server.

3. Preventing I/O operations from becoming bottlenecks.

4. Eliminating single points of failure, thereby ensuring reliability.

5. Achieving parallelism safely and predictably.

N/B: Managing concurrency in connection handling and application design is the key to

building scalable web architectures.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Reasons why JavaScript is Node.js language


When Ryan Dahl designed Node.js, JavaScript was not the language of choice. But after

exploring languages, JavaScript was a good modern language without opinions on streams,

the lesystem, handling binary objects, processes, networking, and other capabilities

expected from a system’s programming language.

JavaScript was only limited to the browser. Therefore, those features were not

implemented, making it easy for Node.js to implement and extend JavaScript.

Node Rigid Principles

Here are some of the rigid principles that guided Ryan Dahl in choosing JavaScript

1. A Node Program/process runs on a single thread, ordering execution through an event

loop.

2. Web applications are I/o intensive, so the focus should be on making I/O fast.

3. Programs ow is always directed through asynchronous callbacks.

4. Expensive operations should be assembled from simpler programs.

The general principle of Node.js is:

Operation Must Never Block.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Node.js is built for speed (high concurrency) and e ciency (minimal resource usage) by

reducing waste, and a waiting process is a wasteful process, especially when waiting for an

I/O operation. Therefore, JavaScript's asynchronous, event-driven design ts neatly into this

model (Node principle).

Node's primary organizational principle is eliminating blocking processes through event-

driven, asynchronous I/O.

If a process's start, stop, and idle state are understood as events that can be subscribed to

and acted upon, we can begin to discuss how extremely complex systems can be

constructed within this new and, at heart, quite simple to grasp model.

What would an environment within which many clients’ jobs are cooperatively scheduled to

look like? And how is this message passing between events handled? Let’s explore two

popular options and discover the one that greatly in uences Node Architectural Design

choice.

Collaboration

Workers could be assigned new tasks in a collaborative environment instead of idling. A

virtual switchboard called a dispatcher is used.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Queueing

We might add a bu er (queue) between the clients and the dispatcher(Libuv) to avoid

overwhelming anyone. This is responsible for managing the prioritized queue of client tasks,

sending and receiving requests and responses from the dispatcher and worker when idle

and when not.

The queue model greatly inspires the Node Architectural Design choice. However, to

implement the queueing model, the Node system is made up of three components:

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

V8 engine

LibUv

Node (Service Manager)

V8 Engine
V8 is Google’s JavaScript engine, written in C++. It compiles and executes JavaScript code

inside a VM (Virtual Machine). The Node event loop is ultimately doing the method of

building up and tearing down a single stack.

LibUv
Node.js internals uses the Libuv library to enforce an asynchronous, event-

driven programming style. The core job of Libuv in Node.js is to provide an event loop and

callback-based noti cations of I/O and other activities.

It is a multi-platform support library focusing on Asynchronous I/O and other core utilities

like timers, non-blocking networking support, asynchronous le system access, child

processes, and more in Node.js.

Speaking of Event Loops, Node.js uses event-driven programming architecture. A program

indicates interest in certain events and responds to them when these events occur. Libuv

handles gathering these events from the operating system and monitoring other sources of

events. Since the event loop runs forever, users can register callbacks to be invoked when

an event occurs.

Here’s a pseudocode explaining how to event loop works:

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

while there are still events to process:


e = get the next event
if there is a callback associated with e:
call the callback

Node.js event loop is a broad topic, and I will create detailed content exploring the Event

loop here. However, this video from ProgrammingWithMosh is a good one.

Node (Service Manager)


Node is the services manager running through the provided instructions and prioritizing

them. When a potentially blocking task is encountered (I/O, timers, and streams), it is

handed over to the dispatcher (the libuv thread pool). Otherwise, the instruction is queued

up for the event loop to pop and execute.

The primary idea of Node.js is that all I/O or time-consuming operations occupy the worker's

pools which the Node service manager will hand over to the dispatcher (the Libuv thread

pool) while the remaining work (Non-I/O) tasks are sent to the single thread of V8.

The Node engine is the services manager running in nitely through the provided

instructions, prioritizing them, and returning all responses via callback to the client.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Let's see how you can create your rst Node.js application. This section will show you how to

run Node.js scripts from the command line.

How to download and install Node.js


First, you need to download and install Node.js. There are di erent ways you can do that. If

you are a beginner, I suggest downloading Node.js from the o cial website.

[image]

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

O cial packages are available on the website for all major platforms (Windows, macOS, and

Linux). Download and install the appropriate package for your system.

After installing Node.js successfully, open your terminal and type the following command to

con rm your installation.

node -v

If you see Node.js with version information as shown below, then you have successfully

installed Node.js on your machine.

You can also con rm the version of NPM (Node Package Manager) that’s installed using the

command below:

npm -v

NPM is always installed with a fresh version of Node.js; you don’t need to install it separately.

Create your rst Node Application.


Now that you have Node installed let’s create our rst Node application, open any text

editor of your choice and type the following scripts in a new index.js le.

console.log("Hello World")

Next, open your terminal to the location of your index.js le and type the following command

to compile and run your code:

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

node index.js

If everything is successful, you should be greeted with Hello World in your terminal as the

output.

Of course, Node doesn’t end there. Next, let’s explore Node.js modules and look at some of

the popular Node.js modules.

A module system allows us to split and include code and import code written by other

developers whenever required.

Eric Raymond proposed the Rule of Modularity: “Developers should build a program out of

simple parts connected by well-de ned interfaces, so problems are local, and parts of the

program can be replaced in future versions to support new features. This rule aims to save

time on debugging complex code that is complex, long, and unreadable.”

One of the main problems with building scalable systems with JavaScript is the lack of

modularity or a standard interface for assembling a coherent program from many smaller

ones. For instance, a typical web application might load dependencies using a sequence of

<script> tags in the <head> section of an HTML document:

<head>
<script src=" leA.js"></script>
<script src=" leB.js"></script>
</head>

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

One problem with this approach is the lack of dynamic inclusion, which requires complicated

hacks. If possible, all potential dependencies must be declared before being used. The

introduced scripts are not encapsulated, leB cannot address leA , and there are

diminishing opportunities for collaboration and reusability.

To solve these problems, Node.js is designed around Modules System, which allows

developers to split codes into di erent les to maintain, organize and reuse code whenever

possible.

A module is nothing but a JavaScript le. Node.js has many built-in modules that are part of

the platform and come with Node.js installation, for example, HTTP, fs, path, and more.

A Node module uses two formats — CommonJS and ESM(EcmaScript). You can get a

detailed comparison of CommonJS and ESM, but a simple di erence lies with how

developers can import and export each module.

CommonJS uses the require method for importing modules and module.exports to export and

expose modules, while ESM uses import to import modules and export to export and expose

modules.

Popular Built-in Node.js Modules


Here are ve popular built-in Node.js Modules and how to use them in your Node.js project.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

1. HTTP

2. Fs

3. Path

4. Process

5. URL

Node HTTP Module

The http module is used to create an HTTP server in Node.js. It is one of the most popular

Node.js modules because almost every web application built with Node.js uses it.

Here’s a simple example of using http module to build a simple web server in Node.js:

const http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('Welcome to this page!');
res.end();
}).listen(3000);

In the code snippet above, I’m using the commonJS require syntax to import the http module

from Node.js.

Next, I call the createServer function from the module to create a web server. After creating

the server, it will call the callback function with the response( res ) and request( req ).

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Next, I use the res property to specify what the server should return when it is called using

the write , writeHead methods.

Lastly, I call the listen function and pass the port number I want the server to listen to. If you

run this program using the following command:

node server.js

If everything is successful, visit [localhost:3000](<http://localhost:3000>) in your browser, and you

should be greeted with Welcome to this page! on your browser.

Node FS Module

The fs is the acronym for File System. It’s used to handle le systems in Node.js. This

module has many di erent methods to handle les in Node.js, using an asynchronous or

synchronous approach.

Here’s a sample script to read the content of a le in Node.js:

In the above code snippet, we use the readFile function from the fs module to read the

content of the test.txt le.

The Path Module

The path includes methods to deal with le paths. Node.js made working with le and

directory paths for Windows, Linux, or Mac operating systems easy.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Here’s a simple code snippet for accessing a speci c le in a directory. Assuming we want to

list all the les in the Documents folder in our system:

//requiring path and fs modules


const path = require('path');
const fs = require('fs');

//joining path of directory


const directoryPath = path.join(__dirname, 'Documents');

//passsing directoryPath and callback function


fs.readdir(directoryPath, function (err, les) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}

//listing all les using forEach


les.forEach(function ( le) {
// Do whatever you want to do with the le
console.log( le);
});
});

In the code snippet above, we required both the fs and path modules since both will be

useful. Next, we use the path.join function from the path module to join the current directory

where we save this JavaScript le we are working with using the global __dirname with the

Documents folder.

Next, we use the readdir function from the fs module to read the directory content we

passed as the parameter. In our case, it's the Documents folder.

Lastly, we loop through all the les and log them to the console using JavaScript forEach .

The Process Module

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

The process module provides information and controls about the current Node.js process.

With the process module, you can control the current Node process.

One of the most popular uses of the process module is to return an object containing the

user environment.

Here’s a sample code snippet to return your application environment variable:

process.env.NODE_ENV
process.env.API_KEY

In the script above, we use the env property of the process module to return the NODE_ENV

and API_KEY de ned in our .env le.

The URL Module

The url module provides utilities for URL resolution and parsing. If you need to parse your

URL, generate an acceptable URL format, or split your URL into a readable part in Node.js,

the url module is your goto module.

Here’s how to split a URL into a readable part in Node.js:

var url = require('url');


var adr = '<http://localhost:3000/default.htm?year=2017&month=february>';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:3000'


console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }


console.log(qdata.month); //returns 'february'

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

First, we require the url module and parse our URL using the parse method from the url

module. Now that the URL is parsed, we can work with di erent parts of the URL, as shown

in the code snippet above.

In many ways, the success of Node.js is due to growth in the number and quality of packages

available to the developer community, distributed via the Node package management

system (NPM).

NPM is a Node package management system and online repository for publishing open-

source Node.js custom or user-created packages. It is also a command-line utility for

interacting with the online repository that aids in package installation, version management,

and dependency management.

In creating a custom package, you can make it private or public for others. We will not cover

private packages in this guide, but we will learn how to install, update, and run scripts using

NPM.

Installing packages

To install any package into your Node.js project, you need the full name of the package you

want to install, then use it with the command as shown below:

npm install is-even

npm is the package manager and a command line utility, install is the command we want to

run, which takes in is-even as the name of the package we will pull from the online repository

and install into our local repository and project.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Updating a package

Assuming you want to update the version of a package you installed earlier. You can use the

following command to achieve it.

npm update [email protected]

You can update a speci c package by specifying the version number or update all packages

using npm update command.

Running your Node project

Professionally, when creating a Node project, you include a package.json le to manage your

dependencies and some project metadata. You can create a blank package.json le using the

following command:

npm init -y

Specifying the -y ag means you want to accept all the defaults. Now, you can add a script

section on your package.json le to run some commands using NPM. Let’s take a look at how

to run a Node project using NPM:

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

{
"name": "tests",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \\"Error: no test speci ed\\" && exit 1",
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}

Look at the script above. The start property inside the scripts object tells NPM how to start

the Node project. Running the start command using NPM will start our Node project:

npm run start

You can specify as many commands you want to run in the scripts section and run it using

the run command in NPM.

Working with Node.js to create APIs is a broad topic because it covers building scalable APIs

and designing enterprise-level APIs in Node.js. We will cover API and API Design for these

backend engineering resources.

However, we will learn how to build a simple web API using the Node http module and

introduce you to popular Node frameworks you can use to build scalable APIs for your

project.

In the previous lesson, we learned about the http module and how you can use it to create a

web server. Here we will build a simple API to demonstrate how to use the http module to

build APIs without any framework.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Setting up Your Development Environment


Create a project directory for your new Node.js project and cd into the directory using the

commands below:

mkdir node-todo-api
cd node-todo-api

Next, initialize a default package.json le to install and manage our dependencies and run

our Node project.

npm init -y

This command will create a new package.json le inside your root directory. Open it and

update it to look like the one below:

{
"name": "tests",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \\"Error: no test speci ed\\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}

The API will perform a basic CRUD (Create, Read, Update, and Delete) operation on an array

of todos since want to keep things very basic and not con gure any database.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

The last part of the setup is using the http module from Node to create a web server for our

API. We have already done something similar above, but let’s review it again.

const http = require('http)


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

server.listen(3000, () => {
console.log('Server is running')
});

The code snippet above creates a simple HTTP server using the createServer method of the

http module from Node.js, and next, we listen to incoming requests on port 3000 .

Create a Temporary Array of Todos


Next, we will create an array of todos that serve as our database to perform the CRUD

operations on it. With this array, we should be able to create new todo, read todo from the

array, update the todo state, and delete the todo when done.

So add the following code to your server.js le to create the array:

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

// Data Source, could be replaced with a real database


const todos = [
{
title: "Todo 1",
desc: "This is my rst Todo",
completed: true,
},

{
title: "Todo 2",
desc: "This is my second Todo",
completed: true,
},

{
title: "Todo 3",
desc: "This is my third Todo",
completed: true,
},

{
title: "Todo 4",
desc: "This is my fourth Todo",
completed: true,
},

{
title: "Todo 5",
desc: "This is my fth Todo",
completed: true,
},
];

To clear confusion, the nal code should look like this inside the server.js le:

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

const http = require('http)


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

// Router will be added here

});

// Data Source, could be replaced with a real database


const todos = [
{
title: "Todo 1",
desc: "This is my rst Todo",
completed: true,
},

{
title: "Todo 2",
desc: "This is my second Todo",
completed: true,
},

{
title: "Todo 3",
desc: "This is my third Todo",
completed: true,
},

{
title: "Todo 4",
desc: "This is my fourth Todo",
completed: true,
},

{
title: "Todo 5",
desc: "This is my fth Todo",
completed: true,
},
];

server.listen(3000, () => {
console.log('Server is running')
});

Creating Routes

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Next, we will create routes on our server to retrieve, create, update, and delete todos from

our temporary database. Create a new routes.js le inside your root directory and add the

following code snippet.

touch routes.js

Open the routes.js le and add the following code snippet before you move on to adding the

other codes explained below:

const router = async function (req, res) {

// Add other codes here

};
module.exports = router;

Get Routes

We will start by creating the GET routes, which we will use to retrieve all todos or a speci c

todo with the ID:

// GET: /api/todos
if (req.url === "/api/todos" && req.method === "GET") {

// set the status code and content-type


res.writeHead(200, { "Content-Type": "application/json" });

// get all todos and send data


res.end(JSON.stringify(todos));
}

The code snippet above retrieves all the todos from our temporary storage using the nd()

method when the request URL equals /api/todos and the request method is GET using the

req object.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Lastly, we return the status code of 200 and the content type of application/json and the todos

data using res.writeHead and res.end , respectively.

Next, we will retrieve a single todo based on the URL and the ID of the URL that’s provided.

Take a look at the code snippet below:

// GET: /api/todos/:id
if (req.url.match(/\\\\/api\\\\/todos\\\\/([0-9]+)/) && req.method === "GET") {
try {
// extract id from url
const id = req.url.split("/")[3];

// get todo from DB


const todo = await todos. nd((todo) => todo.id === id) };

if (todo) {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(todo));
} else {
throw new Error("Todo does not exist");
}
} catch (error) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: error }));
}
}

The code snippet above checks if the request URL matches our regex expression (that’s if it

matched /api/todos/:id , where :id equals any number) and it's a GET then we will nd the

todo using the id and return it as a response, or we return not found exception.

POST Routes

The code snippet below implements the POST request to create new todos in our

temporary database. Take a look at the code implementation below:

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

// POST: /api/todos/
if (req.url === "/api/todos" && req.method === "POST") {
try {
let body = "";

// Listen for data event


req.on("data", (chunk) => {
body += chunk.toString();
});

// Listen for the end event


req.on("end", async () => {
// Create a new todo
await todos.push(JSON.parse(body));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(todos.slice(-1));
});
} catch (error) {
console.log(error);
}
}

The code snippet above checks if the URL is equal to /api/todos and if the request method is

POST . Then we add the data to our temporary database without proper validation.

The request object req implements the Node.js ReadableStream interface. The stream

emits a data and end event, giving us access to the data from the request body. Next, we

listen to the data event and convert the data to a string by concatenating it to the body

variable above. In the end event, we push the body to our array after parsing using

JSON.parse function.

Lastly, we return the last added item in our array using the todos.slice method.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

PUT Routes

Next, we will look at implementing the PUT request in Node.js. Take a look at this code

snippet below for the implementation:

The code snippet above checks if the URL matches our regular expression and if it’s a PUT

request. Then we move to update the todo in our temporary database that matches the

speci ed ID with the new data.

Finally, we returned the updated data as a response. However, if any error is encountered,

we throw new errors.

DELETE Route

Lastly, we will look at implementing the DELETE request in Node.js. Take a look at this code

snippet below for the implementation:

This code block extracts the id from the url , deletes the todo with the matching id , sends

the status code and headers, and closes the request.

Import the Router


Finally, import router.js in your server.js le and call your router function, passing req and res

arguments as shown below:

const router = require("./routes.js");

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


router(req, res);
});

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Below is the full implementation of the server.js le. You can also visit my repository to view

the complete routes.js le:

const http = require('http)


const router = require("./routes.js");

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

// Router will be added here


router(req, res);

});

// Data Source, could be replaced with a real database


const todos = [
{
title: "Todo 1",
desc: "This is my rst Todo",
completed: true,
},

{
title: "Todo 2",
desc: "This is my second Todo",
completed: true,
},

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

{
title: "Todo 3",
desc: "This is my third Todo",
completed: true,
},

{
title: "Todo 4",
desc: "This is my fourth Todo",
completed: true,
},

{
title: "Todo 5",
desc: "This is my fth Todo",
completed: true,
},
];

server.listen(3000, () => {
console.log('Server is running')
});

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

Lastly, we will look at how to test your Node API using Postman. You can use any HTTP client,

like your browser, etc.

Testing your Node API


Start your project using the command below, and if everything works successfully, you

should be greeted with the Server is running message in your terminal:

npm run start

Next, open your Postman and send a GET request to [localhost:3000/api/todos]

(<http://localhost:3000/api/todos>) Endpoint. If everything is properly set up. You should have a

response similar to the one below:

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

As demonstrated, creating scalable APIs with Node.js without any framework is possible. But

it is a di cult task to manage and requires high mastery. You will need to make sure you
cover lots of edge cases and create bug-free codes.

Node.js Essentials - Mastering Backend


Node.js Essentials - Mastering Backend

That is where frameworks come to the rescue. Over the years, Node.js developers have

built frameworks like ExpressJS, NestJS, and AdonisJS to make building enterprise-level and

scalable Node applications easier.

We have already covered some of the popular Node frameworks. You can click the links

above to learn any one of your choices.

Click here to read ExpressJS Ultimate Guide.

Click here to read NestJS Ultimate Guide.

Click here to read AdonisJS Ultimate Guide.

I will advise you to start with ExpressJS and then move to any other framework in the

ecosystem.

Node.js Essentials - Mastering Backend


Want to become a
great Backend
Engineer?

Join Our Academy

Mastering Backend is a great resource for backend engineers. Next-level

Backend Engineering training and Exclusive resources.

You might also like