Introduction to Node.js
The modern web application has really come a long way over the years with the introduction of many popular frameworks such as bootstrap, Angular JS, etc. All of these frameworks are based on the popular JavaScript framework.
But when it came to developing server-based applications, there was a kind of void, and this is where Node.js came into the picture.
Node.js is also based on the JavaScript framework, but it is used for developing server-based applications. While going through the entire tutorial, we will look into Node.js in detail and how we can use it to develop server-based applications.
What is Node.js?
Node.js is an open-source, cross-platform runtime environment used for the development of server-side web applications. Node.js applications are written in JavaScript and can be run on a wide variety of operating systems.
Node.js is based on an event-driven architecture and a non-blocking Input/Output API that is designed to optimize an application’s throughput and scalability for real-time web applications.
Over a long period of time, the framework available for web development were all based on a stateless model. A stateless model is where the data generated in one session (such as information about user settings and events that occurred) is not maintained for usage in the next session with that user.
A lot of work had to be done to maintain the session information between requests for a user. But with Node.js, there is finally a way for web applications to have real-time two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely.
Why use Node.js?
We will have a look into the real worth of Node.js in the coming chapters, but what is it that makes this framework so famous. Over the years, most of the applications were based on a stateless request-response framework. In these sort of applications, it is up to the developer to ensure the right code was put in place to ensure the state of web session was maintained while the user was working with the system.
But with Node.js web applications, you can now work in real-time and have a 2-way communication. The state is maintained, and either the client or server can start the communication.
Features of Node.js
Let’s look at some of the key features of Node.js
- Asynchronous event-driven IO helps concurrent request handling –
This is probably the most significant selling point of Node.js. This
feature basically means that if a request is received by Node for some
Input/Output operation, it will execute the operation in the background
and continue with processing other requests.
This is quite different from other programming languages. A simple example of this is given in the code below
var fs = require('fs'); fs.readFile("Sample.txt",function(error,data) { console.log("Reading Data completed"); });
- The above code snippet looks at reading a file called Sample.txt. In other programming languages, the next line of processing would only happen once the entire file is read.
- But in the case of Node.js the important fraction of code to notice is the declaration of the function (‘function(error,data)’). This is known as a callback function.
- So what happens here is that the file reading operation will start in the background. And other processing can happen simultaneously while the file is being read. Once the file read operation is completed, this anonymous function will be called, and the text “Reading Data completed” will be written to the console log.
- Node uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence the processing of requests within Node also become faster.
- Handling of concurrent requests – Another key functionality of Node is the ability to handle concurrent connections with a very minimal overhead on a single process.
- The Node.js library uses JavaScript – This is another important aspect of development in Node.js. A major part of the development community is already well versed in javascript, and hence, development in Node.js becomes easier for a developer who knows javascript.
- There is an active and vibrant community for the Node.js framework. Because of the active community, there are always keys updates made available to the framework. This helps to keep the framework always up-to-date with the latest trends in web development.
When to Use Node.js
Node.js is best for usage in streaming or event-based real-time applications like
- Chat applications
- Game servers – Fast and high-performance servers that need to processes thousands of requests at a time, then this is an ideal framework.
- Good forcollaborative environment – This is good for environments which manage documents. In a document management environment, you will have multiple people who post their documents and do constant changes by checking out and checking in documents. So Node.js is good for these environments because the event loop in Node.js can be triggered whenever documents are changed in a document managed environment.
- Advertisement servers – Again here you could have thousands of request to pull advertisements from the central server and Node.js can be an ideal framework to handle this.
- Streaming servers – Another ideal scenario to use Node is for multimedia streaming servers wherein clients have request’s to pull different multimedia contents from this server.
Node.js is good when you need high levels of concurrency but less amount of dedicated CPU time.
Best of all, since Node.js is built on javascript, it’s best suited when you build client-side applications which are based on the same javascript framework.
What is a Module in Node.js?
As stated earlier, modules in Node js are a way of encapsulating code in a separate logical unit. There are many readymade modules available in the market which can be used within Node js.
Below are some of the popular modules which are used in a Node js application
- Express framework – Express is a minimal and flexible Node js web application framework that provides a robust set of features for the web and mobile applications.
- Socket.io – Socket.IO enables real-time bidirectional event-based communication. This module is good for creation of chatting based applications.
- Jade – Jade is a high-performance template engine and implemented with JavaScript for node and browsers.
- MongoDB – The MongoDB Node.js driver is the officially supported node.js driver for MongoDB.
- Restify – restify is a lightweight framework, similar to express for building REST APIs
- Bluebird – Bluebird is a fully-featured promise library with a focus on innovative features and performance
Using modules in Node.js
In order to use modules in a Node.js application, they first need to be installed using the Node package manager.
The below command line shows how a module “express” can be installed.
- Once the module has been installed, in order to use a module in a Node.js application, you need to use the ‘require’ keyword. This keyword is a way that Node.js uses to incorporate the functionality of a module in an application.
Let’s look at an example of how we can use the “require” keyword. The below “Guru99” code example shows how to use the require function
var express=require('express'); var app=express(); app.set('view engine','jade'); app.get('/',function(req,res) { }); var server=app.listen(3000,function() { });
- In the first statement itself, we are using the “require” keyword to include the express module. The “express” module is an optimized JavaScript library for Node.js development. This is one of the most commonly used Node.js modules.
- After the module is included, in order to use the functionality within the module, an object needs to be created. Here an object of the express module is created.
- Once the module is included using the “require” command and an “object” is created, the required methods of the express module can be invoked. Here we are using the set command to set the view engine, which is used to set the templating engine used in Node.js.
- Here we are using the listen to method to make the application listen on a particular port number.