Nodejs
Nodejs
Node.JS
What is Node.js?
Node.js applications are written in JavaScript, and can be run within the
Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js also provides a rich library of various JavaScript modules
which simplifies the development of web applications using Node.js to
a great extent.
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
• Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in cAode
execution.
• 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
$ node app.js
Asynchronous Programming
• The function that takes less time will execute first than the function that takes more
time. The faster function does not have to wait for the completion of the slower
function which appears before it sequentially. This makes the overall execution
faster and non-blocking and gives the power to perform multiple tasks at once.
How to do Asynchronous Programming in Node.js?
• In Node.js, doing asynchronous programming is straightforward and easy. Whenever you use any of its modules,
you will find that each module has both synchronous and asynchronous methods.
• Always try to choose an asynchronous method because of its non-blocking nature, which increases
performance and speed.
• If an asynchronous method does not exist for the operation you want to perform then you can use third-party
modules to help you accomplish different types of tasks asynchronously.
• There are some techniques for asynchronous programming in Node.js that you will need to use with asynchronous
methods for control flow.
• There are three main techniques for asynchronous programming in Node.js: callback, promises, and async/await.
What is Callback?
• Callback is an asynchronous equivalent for a function. A callback function is
called at the completion of a given task. Node makes heavy use of callbacks. All
the APIs of Node are written in such a way that they support callbacks.
• For example, a function to read a file may start reading file and return the control
to the execution environment immediately so that the next instruction can be
executed. Once file I/O is complete, it will call the callback function while passing
the callback function, the content of the file as a parameter. So there is no blocking
or wait for File I/O. This makes Node.js highly scalable, as it can process a high
number of requests without waiting for any function to return results.
Blocking Code Example
Non-Blocking Code Example
These two examples explain the concept of blocking and non-blocking calls.
• The first example shows that the program blocks until it reads the file and then only it proceeds to
• The second example shows that the program does not wait for file reading and proceeds to print
"Program Ended" and at the same time, the program without blocking continues reading the file.
Thus, a blocking program executes very much in sequence. From the programming point of view, it is
easier to implement the logic but non-blocking programs do not execute in sequence.
Event Loop
What is the Event Loop?
The event loop is what allows Node.js to perform non-blocking I/O
operations — despite the fact that JavaScript is single-threaded — by
offloading operations to the system kernel whenever possible.
When Node.js starts, it initializes the event loop, processes the provided
input script
• The following diagram shows a simplified overview of the event loop's
order of operations.
• Each phase has a FIFO queue of callbacks to execute. While each
phase is special in its own way, generally, when the event loop enters a
given phase, it will perform any operations specific to that phase, then
execute callbacks in that phase's queue until the queue has been
exhausted or the maximum number of callbacks has executed. When
the queue has been exhausted or the callback limit is reached, the
event loop will move to the next phase, and so on.
• Since any of these operations may schedule more operations and new
events processed in the poll phase are queued by the kernel, poll
events can be queued while polling events are being processed.
Phases Overview
How to use the Node.js REPL
REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows
console or Unix/Linux shell where a command is entered and the system responds with an output
in an interactive mode. Node.js or Node comes bundled with a REPL environment. It performs the
following tasks:
• Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory.
• Loop − Loops the above command until the user presses ctrl-c twice.
Starting REPL
REPL can be started by simply running node on shell/console without any
arguments as follows.
$ node
You will see the REPL Command prompt > where you can type any Node.js command
−
$ node
>
Simple Expression
If var keyword is not used, then the value is stored in the variable and printed. Whereas
if var keyword is used, then the value is stored but not printed. You can print variables
using console.log().
$ node
> x = 20
20
> var y = 30
undefined
> x + y
50
> console.log("Node js")
Node js
undefined
Multiline Expression
$ node
> var i = 0
undefined
> do {
... i++;
... console.log("i: " + i);
... }
while ( i < 5 );
i: 1
i: 2
i: 3
i: 4
i: 5
undefined
>
Underscore Variable
Use of underscore (_) to get the last result −
$ node
> var x = 60
undefined
> var y = 30
undefined
>x+y
90
> var sum = _
undefined
> console.log(sum)
90
undefined
>
Stopping REPL
As mentioned above, you will need to use ctrl-c twice to come out of
Node.js REPL.
EventEmitter
Node.js allows us to create and handle custom events
easily by using events module. Event module includes
EventEmitter class which can be used to raise and handle
custom events.
The emit() function raises the specified event. First
parameter is name of the event as a string and then
arguments. An event can be emitted with zero or more
arguments. You can specify any name for a custom event
in the emit() function.
// get the reference of EventEmitter class of events module
var events = require('events');
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
• Multiple callbacks can be registered against that same event.
Node.js Net Module
• The Net module provides a way of creating TCP servers and TCP
clients.
Modules are the blocks of encapsulated code that communicate with
an external application on the basis of their related functionality.
Modules can be a single file or a collection of multiple files/folders. The
reason programmers are heavily reliant on modules is because of their
reusability as well as the ability to break down a complex piece of code
into manageable chunks.
Modules are of three types:
• Core Modules
• local Modules
• Third-party Modules
const module = require('module_name');
• Core Modules: Node.js has many built-in modules that are part of the
platform and come with Node.js installation. These modules can be
loaded into the program by using the required function.
• Local Modules: Unlike built-in and external modules, local modules
are created locally in your Node.js application. Let’s create a simple
calculating module that calculates various operations.
Filename: calc.js
const calculator = require('./calc');
exports.add = function (x, y) {
return x + y; let x = 50, y = 10;
};
console.log("Addition of 50 and 10 is "
exports.sub = function (x, y) {
+ calculator.add(x, y));
return x - y;
}; console.log("Subtraction of 50 and 10 is "
exports.mult = function (x, y) { + calculator.sub(x, y));
A buffer is a space in memory (usually RAM) that temporarily stores binary data. The purpose of this
space is to help any running entity not lose data during a transfer using a FIFO system.
Buffer in Nodejs
In Nodejs we can manipulate these memory spaces with the module called Buffer built into its core.
Buffers are widely used when working with binary data at the network level. The Nodejs modules and
functionalities work implicitly based on events and manipulation of Buffer / Streams, such as the
core File System or HTTP modules that store the temporary data flow in a Buffer.