About Node.js®
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. In the following "hello world" example, many connections can be handled concurrently. Upon each connection, the callback is fired, but if there is no work to be done, Node.js will sleep.About Node.js®
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. In the following "hello world" example, many connections can be handled concurrently. Upon each connection, the callback is fired, but if there is no work to be done, Node.js will sleep.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
What is Node.js?Node.js is an open source server environment
- Node.js is free
- Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
- Node.js uses JavaScript on the server
Why Node.js?
Node.js uses asynchronous programming!
Here is how PHP or ASP handles a file request:Sends the task to the computer's file system.
- Waits while the file system opens and reads the file.
- Returns the content to the client.
- Ready to handle the next request.
- Ready to handle the next request.
- When the file system has opened and read the file, the server returns the content to the client.
- Node.js eliminates the waiting, and simply continues with the next request.
- Node.js runs single-threaded, non-blocking, asynchronous programming, which is very memory efficient.
What Can Node.js Do?
- Node.js can generate dynamic page content
- Node.js can create, open, read, write, delete, and close files on the server
- Node.js can collect form data
- Node.js can add, delete, modify data in your database
What is a Node.js File?
- Node.js files contain tasks that will be executed on certain events
- A typical event is someone trying to access a port on the server
- Node.js files must be initiated on the server before having any effect
- Node.js files have extension ".js"
Now let us first know what NodeJS is.
Whenever a client requests something from the client side of the application what happens is , the request is first sent to the server and then in that server some processing or calculations goes on for the validation of the client side request and after doing all such validation a response is sent to the client side. Basically for doing all such calculations and processing , this NodeJs framework of JavaScript is used.
For running our web applications outside the client’s browser , NodeJS is basically used as an open-source and cross platform JavaScript runtime environment.For running the server side applications we use this.For building the I/O intensive applications like video streaming sites ,online chatting applications and many other applications , it is used. Many established tech giant companies and newly created start-ups are using NodeJs framework in their company.
In 2009, NodeJs was developed by a guy called Ryan Dahla and the current version of NodeJs is v16.9.0.
Node.js is an open-source, cross-platform JavaScript runtime environment and library for running web applications outside the client's browser. Ryan Dahl developed it in 2009, and its latest iteration, version 15.14, was released in April 2021. Developers use Node.js to create server-side web applications, and it is perfect for data-intensive applications since it uses an asynchronous, event-driven model.
Now that we know what is Node, let's look at why it is so prevalent in web development.
Node.js is a runtime environment that allows JavaScript to be executed on the server side. It is built on the V8 JavaScript engine from Chrome, which compiles JavaScript into efficient machine code. Node.js operates on a single-threaded event-driven architecture, utilizing an event loop to handle multiple concurrent operations without blocking.
When a client sends a request to a Node.js server, the request is added to an event queue. The event loop continuously checks this queue and processes each request. If a request involves an I/O operation, Node.js offloads it to the system kernel, which handles it asynchronously. Once the I/O operation is complete, the kernel notifies Node.js, executing the corresponding callback function.
This non-blocking I/O and event-driven model allows Node.js to handle many simultaneous connections efficiently, making it ideal for building scalable, high-performance network applications.
Why Do We Use NodeJs?
There are many reasons for which we prefer using NodeJs for the server side of our application, some of them are discussed in the following:NodeJs is built on Google Chrome’s V8 engine, and for this reason its execution time is very fast and it runs very quickly.
- There are more than 50,000 bundles available in the Node Package Manager and for that reason developers can import any of the packages any time according to their needed functionality for which a lot of time is saved.
- As NodeJs do not need to wait for an API to return data , so for building real time and data intensive web applications, it is very useful. It is totally asynchronous in nature that means it is totally non-blocking.
- The loading time for an audio or video is reduced by NodeJs because there is better synchronization of the code between the client and server for having the same code base.
- As NodeJs is open-source and it is nothing but a JavaScript framework , so for the developers who are already used to JavaScript, for them starting developing their projects with NodeJs is very easy.
Features of NodeJs
Asynchronous in Nature and Event drivenThe servers made with the NodeJs never waits for the from an API. Without waiting for the data from the API, it directly moves to the next API. So all the APIs of NodeJS are totally non-blocking in nature. In order to receive and track all the responses of the previous API requests, it follows an event driven mechanism. Hence we can say that all the NodeJs API are non-blocking in nature.
With event looping, a single threaded architecture is followed by NodeJs and for this architecture makes NodeJs more scalable. In contrast to other servers, limited threads are created by them for processing the requests. Whereas for the event driven mechanism, the NodeJS servers reply in a non-blocking or an asynchronous manner and for this reason NodeJS becomes more scalable. If we compare NodeJs with other traditional servers like Apache HTTP servers, then we can say NodeJs handles a larger number of requests. A single threaded program is followed by NodeJS and this allows NodeJs to process a huge amount of requests.
Nowadays, scalable software is demanded by most of the companies. One of the most pressing concerns in Software Development is addressed by NodeJs and that is scalability. Concurrent requests can be handled very efficiently using NodeJs. A cluster module is used by NodeJs for managing the load balancing for all the active CPU cores. The most appealing feature of NodeJs is that it can partition the applications horizontally and this partition procedure is mainly achieved by it due to the use of child processes. Using this feature, the distinct app versions are provided to the different target audiences and also for customization it allows them for catering to the client preferences.
V8 JavaScript runtime motor is used by NodeJs and this is also used by Google chrome. A wrapper is provided for the JavaScript by the hub and for that reason the runtime motor becomes faster and for this reason inside NodeJs, the preposition process of the requests also become faster.
Different types of systems like Windows, UNIX, LINUX, MacOS and other mobile devices can use NodeJs. For generating a self-sufficient execution, it can be paired with any appropriate package.
From an engineer's perspective, it is a very important aspect of NodeJs that this framework uses JavaScript Most of the developers are familiar with JavaScript, so for them it becomes very easier to grab NodeJs.
Fast Data Streaming
The processing time of the data that have been transmitted to different streams takes a long time. Whereas for processing the data, NodeJs takes a very short amount of time and it does it at a very fast rate. NodeJs saves a lot of time because the files are processed and uploaded simultaneously by NodeJs. So as a result, the overall speed of data and video streaming is improved by NodeJs.
The data is never buffered in NodeJs application.
Is Node.js a Programming Language?
Node.js is not a programming language; it is a runtime environment allowing you to execute JavaScript code on the server side, outside a web browser. Built on the V8 JavaScript engine from Chrome, Node.js compiles JavaScript into machine code for efficient execution. It extends JavaScript capabilities by providing additional features and libraries for server-side development, such as file system access, network communication, and asynchronous I/O operations.
While JavaScript is the programming language used with Node.js, the runtime environment provides the tools and frameworks to build scalable and high-performance server applications. Node.js’s non-blocking, event-driven architecture makes it ideal for real-time applications, web servers, APIs, and more. In summary, Node.js is a robust environment that leverages JavaScript to enable server-side programming, but it is not a programming language.
Node.js Architecture
Now that we established what is Node, let’s dig into its architecture. Node.js operates on a single-thread, allowing it to handle thousands of simultaneous event loops. Here’s a diagram, provided by Sinform.com, that best illustrates Node.js architecture.
Now, let's go through each part of Node.js to get a better understanding of the server-side platform as a whole.
Modules
Modules are like JavaScript libraries that can be used in a Node.js application to include a set of functions. In order to include a module in a Node.js application, use the require() function with the parenthesis containing the name of the module.// CREATING A WEB SERVER i||
// Include modules i
var http =require(‘http’); 3
var server = |
http.createServer(function(req, res){//write your code here |
i
server.listen(2000);
Include a module in Node.js
Node.js has many modules that provide the basic functionality needed for a web application. Some of them are mentioned in this table:Fig: Node.js modules table
Console
The console is a module that provides a method for debugging that is similar to the basic JavaScript console provided by internet browsers. It prints messages to stdout and stderr.// WRITING “hello world” to consoleconsole.log(hello world’);
Cluster
Node.js is built-on on the concept of single-threaded programming. Cluster is a module that allows multi-threading by creating child processes that share the same server port and run simultaneously.A cluster can be added to an application in the following way:Add cluster in Node.js
Global
Global objects in Node.js are available in all modules. These objects are functions, modules, strings, etc. Some Node.js global objects are mentioned in the table below:Global objects table
Error Handling
Node.js applications experience four types of errors.Node.js errors
Errors in Node.js are handled through exceptions. For example, let's handle the error that would occur when we divide a number by zero. This error would crash the Node.js application, so we should handle this error to continue with the normal execution of the application.try {varm=1;varn =1/0;}catch (err) {// Handling the error here.}
Node.js error handling
Streaming- Readable: These are the types of streams from which data can be read
- Writable: These are the types of streams to which data can be written
- Duplex: These are both readable and writable streams
- Transform: Streams that can manipulate the data while it is being read or writtenBuffer
var buf = Buffer.alloc(10);
Node.js buffer
Domain- Internal Binding: Error emitter executes its code inside the run method
- External Binding: Error emitter is explicitly added to a domain via its add method
dns.resolve()
DNS resolve
DNS module is also used for performing name resolution without a network communication by using the following method:dns.lookup()
DNS lookup
Debugger$ node inspect myscript.jsi
Fig: Node.js debugger
Now that we are familiar with the main parts of Node.js let's go ahead and learn about the Node.js Express framework.Node.js Express Framework- Used for designing single-page, multi-page, and hybrid web applications
- Allows developers to set up middlewares for responding to HTTP Requests
- Defines a routing table that is used to perform different actions based on the HTTP method and URL
- Allows dynamic rendering of HTML Pages based on passing arguments to templates
var express = require('express');var app = express();app.get('/', function (req, res) {res.send('Hello World");})var server = app.listen(808], function () {VEId [o S ERT=TaV=oTe [o [f=S @ NoTe lo (9=NGl oTelg ERT-TgVT-To[o [{=11T@ Nololadconsole.log("Example app listening at http://%s:%s", host, port)})
Node.js Express framework, "Hello World."
- var express: Importing Express framework into our Node.js application
- app.get(): Callback function with parameters ‘request’ and ‘response’
- The request object: It represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc.
- The response object: It represents the HTTP response that an Express app sends when it gets an HTTP request.
- The application will listen to the defined port, which in this case is "8081," and variables "host" and "port" will contain the address and the port, respectively.
- console.log: This is to show the address and port in the command prompt or terminal.
- Having learned about the Express framework, let's now move on to the use cases of Node.js.
Applications of Node.js
- Web Servers: Node.js is ideal for building fast and scalable web servers that handle numerous simultaneous connections with high throughput.
- Real-Time Applications: It excels in real-time applications like chat applications, online gaming, and live collaboration tools, where real-time data updates are crucial.
- APIs and Microservices: Node.js is commonly used to create RESTful APIs and microservices, facilitating communication between services in a distributed architecture.
- Single-Page Applications (SPAs): Node.js serves and handles the backend logic for single-page applications, enhancing user experience with smooth, dynamic content updates.
- Streaming Applications: Its asynchronous nature makes Node.js suitable for data streaming applications, such as video streaming services or real-time data processing.
- Command-Line Tools: Developers use Node.js to create command-line tools and scripts that automate various tasks, leveraging its rich ecosystem of packages.
- Internet of Things (IoT): Thanks to its event-driven architecture, Node.js is used in IoT applications to handle data from numerous devices in real time.