Table of Contents

Nodejs Tutorial

What is Back-End?

The backend is the server side of your website. It stores and organizes your data and makes sure everything works properly on the client side of your website.

It is the part of the website that you cannot see or interact with. The part of the software that does not have direct contact with the user.

Parts and functionality developed by back-end designers are accessed indirectly by users through front-end applications.

Activities such as creating APIs, building libraries, and working with system components without a user interface.

The backend, also called the server side, consists of servers that serve data on demand, applications that host the data, and databases that organize the information. For example, when a customer searches for shoes on her website, she interacts with the front end.

Once you have selected the desired products, added them to your shopping cart and confirmed the purchase, the information will be saved in a database on our server.

A few days later, when the customer confirms the delivery status, the server retrieves the relevant information, updates it with the tracking data, and displays it via the frontend.

What is 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.

Introduction to Node.js?

Node.js is an open-source, cross-platform, JavaScript runtime environment for running JavaScript code outside the browser.

Note that Node.js is neither a framework nor a programming language. Most people are confused and understand that it is a framework or a programming language.

Using Node.js to build backend services such as APIs for web apps and mobile apps is Common. Used by big companies like Paypal, Uber, Netflix and Walmart.

Node.js is a server-side platform based on Google Chrome's JavaScript engine (V8 engine). Node.js was developed by Ryan Dahl in 2009.

Node.js is a platform based on Chrome's JavaScript runtime for easily building fast and scalable network applications.

Using an event-driven, non-blocking I/O model, Node.js is lightweight and efficient, making it ideal for data-intensive real-time applications running on distributed devices.

Applications are written in JavaScript and can be run within Node.

Node.js = Runtime Environment + JavaScript Library

In the end, you will build your own AI from scratch using Python code.

Different parts of Node.js?

Following are the parts of the Node.js:-
1. Modules
2. Debugger
3. Buffer
4. Streaming
5. DNS
6. Domain
7. Global
8. NET
9. Error Handling
10. Crypto
11. Callback
12. Add-ons
13. Cluster
14. Console

Features of Node.js?

Following are the features of node.js:-

1. Single Thread Node.js is single threaded. It is based on a "single threaded event loop model" architecture that can handle multiple client requests.

The main event loop is run by a single thread, but in the background I/O work is done in a separate thread.

This is because the Node API input/output operations are asynchronous (non-blocking design) to accommodate event loops. The event loop allows node.js to perform all non-blocking operations.

2. Asynchronous Node.js is asynchronous by default. H. Works non-blocking. That is, when a client makes a request to the server, a single thread handles that request.

If not, check if the request involves database interaction. The request is processed and the server returns a response to the client.

The thread is ready to handle the next request.

3. Event-Driven The concept of event-driven is similar to that of callback functions in asynchronous programming.

The only difference is that as soon as the asynchronous function returns the result, the callback function will be executed and the event will be raised in the associated event handler.

Node provides a module called "Event" consisting of an "EventEmitter" class that gives you the power to implement event-driven programming.

An event handler is a function that is called when an event occurs. The main loop listens for event triggers and calls the appropriate event handler.

The EventEmitter consists of various methods, one of which is emit(). that will trigger the event. Emit() has the first argument as the name of the event, the second argument is used to pass the data.

The on() method listens for and executes published events. Event-driven programming makes Node.js extremely fast and highly performant.

4. Open Source Node.js is open source. In other words, it's free to use. Depending on your platform, you can install Node.js from https://nodejs.org/en/.

5. Performance Node.js is based on Google Chrome's V8 JavaScript engine, which helps speed up code execution.

The engine compiles JavaScript code into machine code. This makes the code implementation efficient and fast.

Concepts like asynchronous programming and the way it works with non-blocking I/O operations make it performant. Node.js is very fast due to its heavy use of events.

6. Highly Scalable Node.js applications are highly scalable because they are asynchronous (non-blocking).

Node.js works in a single thread and starts processing by the time a single request arrives and is ready to process the next request. Once the response is prepared, it is sent back to the client.

7. Node Package Manager (NPM) As you know, the Node Package Manager is the package manager for the Node JavaScript runtime environment and a recommended feature of the Node.js installer.

This is the world's largest online repository. It also manages the project's local dependencies.

There are about 50,000-80,000 packages in public online repositories.

8. No buffering With the concept of callback functions, Node.js applications output data in blocks. Therefore, users can more easily prepare and retrieve data as they do not have to wait for the entire process to complete.

Reduce total time required for processing. B. When uploading audio or video files. It never buffers data.

9. Caching Node.js has quite a few advantages when it comes to caching. Supports module caching. The first time a Node.js module is requested, it is cached in application memory.

The cache allows the application to load her web pages faster and respond smoothly to the user, without having to run the code again.

10. License Node.js is licensed under the MIT license.

What is Express?

Express is the most popular node web framework and the underlying library for many other popular node web frameworks.

● Write handlers for requests that use different HTTP verbs at different URL paths (routes).

● Integrates with the "view" rendering engine to populate templates and generate responses.

● Specify general web application settings, such as the port to use for connections and the location of the template used to render the response.

● Add additional request processing "middleware" at any point in the request processing pipeline.

Express itself is fairly minimal, but developers have created compatible middleware packages to address nearly any web development problem.

There are libraries that deal with cookies, sessions, user logins, URL parameters, POST data, security headers, etc.

Express.js (Express) sits on top of Node.js and it adds functionality and simplicity to Node.js.

Introduction to MongoDB?

MongoDB is a document-oriented database. This means that it doesn’t use tables and rows to store its data, but instead collections of JSON-like documents.

These documents support embedded fields, so related data can be stored within them.

MongoDB is also a schema-less database, so we don’t need to specify the number or type of columns before inserting our data.

A. MongoDB is a document-oriented database. This means that it doesn’t use tables and rows to store its data, but instead collections of JSON-like documents.

These documents support embedded fields, so related data can be stored within them.

MongoDB is also a schema-less database, so we don’t need to specify the number or type of columns before inserting our data.

MongoDB Features:

Document Oriented: MongoDB stores main topics in a minimal number of documents, rather than splitting them into multiple relational structures like RDBMS. For example, store all computer information in a single document called computer, rather than separate relational structures such as CPU, RAM, and disk.

It will select the one that matches the query, which is inefficient. Indexing is therefore essential for efficient searching, and MongoDB uses it to process large amounts of data in a very short time.

Scalability: MongoDB scales out horizontally using sharding (dividing data across different servers). Data is divided into chunks using shard keys, and these chunks are evenly distributed across shards across many physical servers. Additionally, you can add new machines to the running database.

Replication and High Availability: MongoDB makes data highly available by providing multiple copies of data on different servers. Redundancy protects your database from hardware failures.

If one server goes down, you can easily retrieve the data from other active servers that stored the data.

Aggregate: Aggregate operations process records and return a calculated result. Similar to the group by clause in SQL. Some aggregation expressions are sum, avg, min, max, etc.

Here’s a table summarizing the different terms:

SQL Server MongoDB
Database Database
Table Collection
Row Document
Column Field
Index Index

Q. Why is node.js in demand?

Following are the reasons:-

1. Node.js is easy to learn. This is one of the most important contributions to its spread. Knowledge of JavaScript is common for many developers.

Node.js uses JavaScript. As such, learning Node.js is relatively easy, and you can be up and running in just a few weeks of learning.

If you don't know JavaScript, Node.js takes a little while to learn, but it's still manageable. So learning Node.js is not that difficult.

2. Scalability provided Node.js was built with scalable network applications in mind. Node.js can handle many concurrent requests.

This is the main reason why it has become so popular among developers and big companies. It can handle many concurrent requests without overloading the server.

The callback will only be triggered after a request, but Node.js will go to sleep when there are no more jobs to run.

Node.js is online only when needed. This avoids unnecessary usage of RAM.

3. The mobile-friendly, cross-platform, developer-friendly nature of Node.js.

With the ability to create flexible apps that run smoothly on any platform, including Linux, Windows and Mac OS, Node.

I'm all for js. In recent years, cross-platform application development has increased. The worry that my application won't run on other operating systems is gone thanks to Node.js.

This allowed developers to create apps that ran on different platforms with little or no modification.

4. Node.js is lightweight and fast. Node.js uses Google's V8 JavaScript engine written in C++. The engine is a powerful open source JavaScript and WebAssembly engine.

This engine was developed by The Chromium Project for Google Chrome and Chromium browsers.

The V8 engine handles memory allocation, compiles and executes JavaScript. Use a just-in-time (JIT) compiler to compile JavaScript into machine code before executing it.

Node.js uses a non-blocking model when performing operations. Node.js has published a full article on blocking and non-blocking models here.

Process requests made in a single asynchronous thread. This reduces both CPU workload and memory. This makes the app lightweight.

5. Many hosting providers are available. With growth over the last few years, many cloud-based hosting providers and web servers have added a fairly basic way to host Node.js code.

These hosting providers include Heroku, Amazon Web Services, and DigitalOcean. There are also many detailed and easy instructions.

6. Highly scalable Node.js doesn't provide everything you need at once. Instead, adjust what you want or add what you want.

This will prevent unnecessary libraries. Npm - Node Package Manager is the default package manager for Node.js.

Here you can browse and install over 1 million open source packages. It can also be used to identify and install project dependencies.

7. Its Caching Capabilities Node.js provides the ability to cache individual modules. Caching is saving data for future requests.

When a request is made for a module, it comes from the cache, not from the main server. This will make your app load faster and be more responsive.

Q. Future of Node.js?

Node.js is evolving day by day as a fast, responsive, high-performance server-side framework. The list of companies using Node.js is constantly growing.

It has over 300 well-known companies such as PayPal, Netflix, LinkedIn, Medium, Trello, Uber, Zendesk, and many others.

Zendesk, and many others. It is sure that this platform will continue to grow in popularity for years to come. As mentioned earlier, many IT giants use this platform.

Few open source projects have received such strong support from the world's leading companies. And this is a testament to the great potential of Node.js.

Some stats to demonstrate the promising future of Node.js:

=> More than 30 million online sites use Node.js

=> Node.js is currently used in more than 85 countries

=> Node.js ensured a decrease of loading time by 60%

=> Organizations that applied Node.js reported a 58% reduction in development costs

In short, the future of Node is bright and shining. Node.js is an ideal technology for programmers and plays an important role in the technology stack.

The first and best choice for creating interactive games, chat programs, collaboration tools, instant messaging and more.

The platform will certainly remain a leader in this industry for years to come.

Q. How to set up an http server with node.js?

We can setup a basic http server with the following steps:

First, we require the "http" module to use it by following line:-
const http = require("http")

Second, we need to use a function in "http" named "createServer" to actually
create a server and storing it in a variable named "server"
const server = http.createServer()

Then, we'll pass the callback function to it and the callback takes two objects
as arguments.

The request and response objects which have information about incoming request and outgoing responses.

const server = http.createServer(function (request, response) {
})

Then, we'll write response.write to write the response after a request is
received and response.end to close the connection:

const server = http.createServer(function (request, response) {
response.write("Greetings from Madrid Software!");
response.end();
});

After this, we have to listen the server, so we'll pass the port (ex: 8000) to
it by following line:
server.listen(8000);

And finally, our server has been setup with node.js and the overall code will
look like this;
const http = require("http")
const server = http.createServer(function (request, response) {
response.write("Greetings from Madrid Software!");
response.end();
});
server.listen(8000);

Interview Questions

A Node.js application creates a single thread on its invocation. Whenever Node.js receives a request, it first completes its processing before moving on to the next request.

Node.js works asynchronously by using the event loop and callback functions, to handle multiple requests coming in parallel.

An Event Loop is a functionality which handles and processes all your external events and just converts them to a callback function.

It invokes all the event handlers at a proper time. Thus, lots of work is done on the back-end, while processing a single request, so that the new incoming request doesn't have to wait if the processing is not complete.

While processing a request, Node.js attaches a callback function to it and moves it to the back-end. Now, whenever its response is ready, an event is called which triggers the associated callback function to send this response.

Q. What is callback hell in Node.js?

The callback hell contains complex nested callbacks. Here, every callback takes an argument that is a result of the previous callbacks.

In this way, the code structure looks like a pyramid, making it difficult to read and maintain.

Also, if there is an error in one function, then all other functions get affected.

An asynchronous function is one where some external activity must complete before a result can be processed; it is "asynchronous" in the sense that there is an unpredictable amount of time before a result becomes available.

Such functions require a callback function to handle errors and process the result.

Example:
/**
* Callback Hell
*/
getData(function(a){
getMoreData(a, function(b){
getMoreData(b, function(c){
getMoreData(c, function(d){
getMoreData(d, function(e){
...
});
});
});
});
});

Q. Is Node.js entirely based on a single-thread?

Yes, it is true that Node.js processes all requests on a single thread. But it is just a part of the theory behind Node.js design.

In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously.

Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance.

JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.

To explain it practically, let's assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution.

Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.

Q. How does Node.js handle child threads?

Node.js is a single threaded language which in background uses multiple threads to execute asynchronous code.

Node.js is non-blocking which means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads. That is handled by Node.js run-time.

Nodejs Primary application runs in an event loop, which is in a single thread.

Background I/O is running in a thread pool that is only accessible to C/C++ or other compiled/native modules and mostly transparent to the JS.

Node.js does support forking multiple processes ( which are executed on different cores ).

It is important to know that state is not shared between master and forked process.

We can pass messages to forked process ( which is different script ) and to master process from forked process with function send.

Q. If Node.js is single threaded then how it handles concurrency?

Node js despite being single-threaded is the asynchronous nature that makes it possible to handle concurrency and perform multiple I/O operations at the same time.

Node js uses an event loop to maintain concurrency and perform non-blocking I/O operations.

As soon as Node js starts, it initializes an event loop. The event loop works on a queue (which is called an event queue) and performs tasks in FIFO (First In First Out) order.

It executes a task only when there is no ongoing task in the call stack. The call stack works in LIFO(Last In First Out) order.

The event loop continuously checks the call stack to check if there is any task that needs to be run. Now whenever the event loop finds any function, it adds it to the stack and runs in order.

Example:
/**
* Concurrency
*/
function add(a, b) {
return a + b;
}
function print(n) {
console.log(`Two times the number ${n} is ` + add(n, n));
}
print(5);

Here, the function print(5) will be invoked and will push into the call stack.

When the function is called, it starts consoling the statement inside it but before consoling the whole statement it encounters another function add(n,n) and suspends its current execution, and pushes the add function into the top of the call stack.

Now the function will return the addition a+b and then popped out from the stack and now the previously suspended function will start running and will log the output to console and then this function too will get pop from the stack and now the stack is empty. So this is how a call stack works.

Q. How Node.js read the content of a file?

The "normal" way in Node.js is probably to read in the content of a file in a non-blocking, asynchronous way.

That is, to tell Node to read in the file, and then to get a callback when the file-reading has been finished. That would allow us to hand several requests in parallel.:

/**
* read_file.js
*/
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(3000);

Q. What are the middleware functions in Node.js?

A. Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application's request-response cycle. Middleware functions can perform the following tasks:

• Execute any code.

• Make changes to the request and the response objects.

• End the request-response cycle.

• Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

The following figure shows the elements of a middleware function call:

Middleware functions that return a Promise will call next(value) when they reject or throw an error. next will be called with either the rejected value or the thrown Error.

Q. What is Node.js Process Model?

Node.js 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 doesn't have to wait for the request to complete and is free to handle the next request.

When asynchronous I/O work completes then it processes the request further and sends the response.