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

nodejs

Node.js is a server-side runtime environment built on Chrome's V8 JavaScript Engine, designed for building fast and scalable network applications using an event-driven, non-blocking I/O model. It supports various application types, including I/O bound and real-time applications, and utilizes modules for code reusability. Key features include asynchronous APIs, high scalability, and a robust package management system through NPM.

Uploaded by

yash borkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

nodejs

Node.js is a server-side runtime environment built on Chrome's V8 JavaScript Engine, designed for building fast and scalable network applications using an event-driven, non-blocking I/O model. It supports various application types, including I/O bound and real-time applications, and utilizes modules for code reusability. Key features include asynchronous APIs, high scalability, and a robust package management system through NPM.

Uploaded by

yash borkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

 What is Nodejs :

Node.js is a server-side runtime environment built on Google Chrome's JavaScript Engine


(V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v20.9.0.
Node.js is a cross-platform (run on Windows, Linux, Unix, macOS, and more), open-source,
back-end JavaScript runtime environment, that executes JavaScript code outside a web
browser.

Defination:

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model that
makes it lightweight and efficient, perfect for data-intensive real-time applications that run
across distributed devices.

 Features of Node.js :-
1. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous,
that is, non-blocking. It essentially means a Node.js based server never waits for an
API to return data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the previous
API call.
2. Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is
very fast in code execution.
3. Single Threaded but Highly Scalable − Node.js uses a single threaded model with
event looping. Event mechanism helps the server to respond in a non-blocking way
and makes the server highly scalable as opposed to traditional servers which create
limited threads to handle requests. Node.js uses a single threaded program and the
same program can provide service to a much larger number of requests than
traditional servers like Apache HTTP Server.
4. No Buffering − Node.js applications never buffer any data. These applications simply
output the data in chunks.
5. License − Node.js is released under the MIT license.

 Where to Use Node.js :-


1. I/O bound Applications
2. Data Streaming Applications
3. Data Intensive Real-time Applications (DIRT)
4. SON APIs based Applications
5. Single Page Applications

 Creating Node.js Application

To create a "Hello, World!" web application using Node.js, you need the following three
important components −

Import required modules − We use the require directive to load Node.js modules.

Create server − A server which will listen to client's requests similar to Apache HTTP
Server.

Read request and return response − The server created in an earlier step will read the
HTTP request made by the client which can be a browser or a console and return the
response.

Step 1 - Import Required Module

var http = require("http");

Step 2 - Create Server

We use the created http instance and call http.createServer() method to create a server
instance and then we bind it at port 3000 using the listen method associated with the server
instance. Pass it a function with parameters request and response.

The createserver() method has the following syntax −

http.createServer(requestListener);

listener = function (request, response) {

response.writeHead(200, {'Content-Type': 'text/html'});

response.end('<h2 style="text-align: center;">Hello World</h2>'); };


Step 3 - Testing Request & Response

http = require('node:http');

listener = function (request, response) {

response.writeHead(200, {'Content-Type':'text/html'});

response.end('<h2 style="text-align:center;">Hello World</h2>'); };

server = http.createServer(listener);

server.listen(3000);

console.log('Server running at http://127.0.0.1:3000/');

In the PowerShell terminal, enter the following command.

PS D:\nodejs> node hello.js

Server running at http://127.0.0.1:3000/

 Event loop

Even though JavaScript is single threaded, Node.js employs event loop to perform
asynchronous non-blocking I/O operations, by delegating the operations to the system kernel
whenever possible. Most modern OS kernels are multi-threaded, capable of handling multiple
operations by executing them in the background. When the current operation is completed,
the kernel informs Node.js so that the appropriate callback may be added to the poll queue to
eventually be executed.

The event loop is initialized as soon as Node.js starts, either by providing a .js script or in
REPL

mode. The order of operations of the event loop are shown in the figure below –

The Timers phase executes callbacks scheduled by setTimeout() and setInterval(). The
pending callbacks phase executes I/O callbacks deferred to the next loop iteration.

The poll phase has two main functions:

(a) calculating how long it should block and poll for I/O, and

(b) processing events in the poll queue. Node.js retrieves new I/O events and executes I/O
related callbacks in this phase.

The check phase executes the callbacks immediately after the poll phase has completed. If the
poll phase becomes idle and scripts have been queued with setImmediate() timer. The event
loop continues to the check phase rather than waiting. The libuv library is a part of Node.js
runtime, playing the role of providing support for handling asynchronous operations.
The V8 engine handles the execution of JavaScript code, whereas the Libuv library utilizes
the native mechanism of the respective operating system to hanle asynchronous operations.

Finally, the close callbacks phase handles the callbacks registered with close event such as
socket.on(‘close’, function). The close event will be emitted if the socket is closed abruptly,
otherwise it will be emitted by process.nextTick() method to defer the execution of a function
until the next iteration of the event loop.

Before beginning the next run of the event loop, Node.js checks if it is waiting for any
asynchronous I/O or timers. If there aren’t any, the runtime shuts down cleanly.

 Node.js – Modules

A module in Node.js is a collection of independent and reusable code that can be imported
into any Node.js application. As the name suggests, modules enable a modular and structured
approach for developing a Node.js application.

Types of Modules :-

1. Third-party modules

These modules are developed by independent developers and made available for use
on

the NPM repository. You should install a module either globally or locally in a
Node.js

project folder, if you want to incorporate its functionality in your application.


The Express module is an example of such a module. To install, use any of the
following

commands −

npm install express -g //install globally

or

npm install express –save //install locally

You can then import the installed module in your application. For example –

var express = require('express');

2. Built-in modules

The Node.js runtime software comes with the V8 JavaScript engine, bundled with a
number of core modules, that perform important server-side tasks, such as managing
event loop, perform file IO and operating system-specific functions etc. The examples
of built-in or core modules are http, fs, console etc. These modules are pre-installed,
but you must import them with require() function (except for a few modules such as
process, buffer and console modules, they are global objects). For example −

var fs = require('fs');

3. Local modules

A local module is a .js file, which stores definition of one or functions or classes
required for your Node.js application. Such a module is present locally in the same
Node.js application folder, which also should be included in the application with
require() function.

Every .js file in a Node.js application has a special module object. It’s exports
property exposes a certain function, object or a variable from the .js file to the code
outside.

 Node.js - NPM
NPM − an acronym for Node Package Manager, refers to the Command line utility to install
Node.js packages, perform version management and dependency management of Node.js
packages. It also provides an online repository for node.js packages/modules

Install Package Locally

npm install <Module Name>

npm install express

var express = require('express');

Install Package Globally

Globally installed packages/dependencies are stored in system directory.

npm install express -g

Update Package

npm update <package name>

Uninstall Packages

npm uninstall <package name>

 Node.js - Streams

What are Streams :

A stream is a collection of data. However, unlike an array or a string, the entire data in a
stream object is not stored at once in the memory. Instead, a single chunk of data from the
stream is brought into the memory, at a time. It makes streams more efficient. Node.js
applications are best suited for developing data streaming applications.

Types of streams :-

Node.js processes four fundamental types of streams −

Writable − streams to which data can be written.

Readable − streams from which data can be read.

Duplex − streams that are both Readable and Writable.


Transform − Duplex streams that can modify or transform the data as it is written and read.

Readable Stream

The file object acts as a stream from which the data can be read in a chunk of specific size.

Writable Stream

The createWriteStream() function from fs module creates an object of writable stream. Its
write() method stores the data in the file given to the createWriteStream() function as an
argument.

Piping the Streams

Piping is a mechanism where we provide the output of one stream as the input to another
stream. It is normally used to get data from one stream and to pass the output of that stream to
another stream. There is no limit on piping operations.

Chaining the Streams

Chaining is a mechanism to connect the output of one stream to another stream and create a
chain of multiple stream operations.

basic Node.js script that simply prints "Hello, World!" to the console

// Importing the built-in 'http' module

const http = require('http');8

// Creating a server instance

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

// Setting the response header

res.writeHead(200, {'Content-Type': 'text/plain'});

// Sending the response body

res.end('Hello, World!\n');
});

// Listening on port 3000

server.listen(3000, '127.0.0.1', () => {

console.log('Server running at http://127.0.0.1:3000/');

});

You might also like