# Nodejs Interview Questions ## ***What is Node.js?*** Node.js is an open-source server side runtime environment built on Chrome\'s V8 JavaScript engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript. <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## 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. <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***What are the data types in Node.js?*** Just like JS, there are two categories of data types in Node: Primitives and Objects. *Primitives* * String * Number * Bigint * Boolean * Undefined * Null * Symbol *Objects* - Function - Array - `Buffer`: Node.js includes an additional data type called Buffer (not available in browser\'s JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network. `Buffer` is a class. * other regular objects <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***What does the runtime environment mean in Node.js?*** The Node.js runtime is the software stack responsible for installing your web service\'s code and its dependencies and running your service. The Node.js runtime for App Engine in the standard environment is declared in the `app.yaml` file: ```js runtime: nodejs10 ``` The runtime environment is literally just the environment your application is running in. This can be used to describe both the hardware and the software that is running your application. How much RAM, what version of node, what operating system, how much CPU cores, can all be referenced when talking about a runtime environment. <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***How do Node.js works?*** <p align="center"> <img src="https://github.com/minhtan7/nodejs-interview-questions/blob/master/assets/event-loop.png?raw=true" alt="Node Architecture" width="800px" /> </p> Node is completely event-driven. Basically the server consists of one thread processing one event after another. A new request coming in is one kind of event. The server starts processing it and when there is a blocking IO operation, it does not wait until it completes and instead registers a callback function. The server then immediately starts to process another event (maybe another request). When the IO operation is finished, that is another kind of event, and the server will process it (i.e. continue working on the request) by executing the callback as soon as it has time. So the server never needs to create additional threads or switch between threads, which means it has very little overhead. If you want to make full use of multiple hardware cores, you just start multiple instances of node.js Node JS Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model. Node JS Processing model mainly based on Javascript Event based model with Javascript callback mechanism. **Single Threaded Event Loop Model Processing Steps:** * Clients Send request to Web Server. * Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests. * Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”. * Node JS Web Server internally has a Component, known as “Event Loop”. Why it got this name is that it uses indefinite loop to receive requests and process them. * Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model. * Event Loop checks any Client Request is placed in Event Queue. If no, then wait for incoming requests for indefinitely. * If yes, then pick up one Client Request from Event Queue * Starts process that Client Request * If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client. * If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach * Checks Threads availability from Internal Thread Pool * Picks up one Thread and assign this Client Request to that thread. * That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop * Event Loop in turn, sends that Response to the respective Client. <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***What is the difference between Node.js, AJAX, and JQuery?*** Node.js is a javascript runtime that makes it possible for us to write back-end of applications. Asynchronous JavaScript and XML(AJAX) refers to group of technologies that we use to send requests to web servers and retrieve data from them without reloading the page. Jquery is a simple javascript library that helps us with front-end development. <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***What is callback function in Node.js?*** In node.js, we basically use callbacks for handling asynchronous operations like — making any I/O request, database operations or calling an API to fetch some data. Callback allows our code to not get blocked when a process is taking a long time. ```javascript function myNew(next){ console.log("Im the one who initates callback"); next("nope", "success"); } myNew(function(err, res){ console.log("I got back from callback",err, res); }); ``` <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***What is callback hell in Node.js?*** `Callback hell` is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the other. 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. ```javascript getData(function(a){ getMoreData(a, function(b){ getMoreData(b, function(c){ getMoreData(c, function(d){ getMoreData(d, function(e){ ... }); }); }); }); }); ``` ## Q. ***What are Promises in Node.js?*** It allows to associate handlers to an asynchronous action\'s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise for the value at some point in the future. Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete). The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states: * pending - The initial state of a promise. * fulfilled - The state of a promise representing a successful operation. * rejected - The state of a promise representing a failed operation. Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again). **Creating a Promise** ```javascript var myPromise = new Promise(function(resolve, reject){ .... }) ``` <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***What is asynchronous programming in Node.js?*** Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. When the work is complete, it notifies the main thread (as well as whether the work was completed or failed). There are numerous benefits to using it, such as improved application performance and enhanced responsiveness. <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***What is the difference between Asynchronous and Non-blocking?*** **1. Asynchronous** The architecture of asynchronous explains that the message sent will not give the reply on immediate basis just like we send the mail but do not get the reply on an immediate basis. It does not have any dependency or order. Hence improving the system efficiency and performance. The server stores the information and when the action is done it will be notified. **2. Non-Blocking** Nonblocking immediately responses with whatever data available. Moreover, it does not block any execution and keeps on running as per the requests. If an answer could not be retrieved then in those cases API returns immediately with an error. Nonblocking is mostly used with I/O(input/output). Node.js is itself based on nonblocking I/O model. There are few ways of communication that a nonblocking I/O has completed. The callback function is to be called when the operation is completed. Nonblocking call uses the help of javascript which provides a callback function. * **Asynchronous VS Non-Blocking** 1) Asynchronous does not respond immediately, While Nonblocking responds immediately if the data is available and if not that simply returns an error. 2) Asynchronous improves the efficiency by doing the task fast as the response might come later, meanwhile, can do complete other tasks. Nonblocking does not block any execution and if the data is available it retrieves the information quickly. 3) Asynchronous is the opposite of synchronous while nonblocking I/O is the opposite of blocking. They both are fairly similar but they are also different as asynchronous is used with a broader range of operations while nonblocking is mostly used with I/O. <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***What is typically the first argument passed to a Node.js callback handler?*** The first argument to any callback handler is an optional error object ```javascript function callback(err, results) { // usually we'll check for the error before handling results if(err) { // handle error somehow and return } // no error, perform standard callback handling } ``` <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***Why to use Express.js?*** ExpressJS is a prebuilt NodeJS framework that can help you in creating server-side web applications faster and smarter. Simplicity, minimalism, flexibility, scalability are some of its characteristics and since it is made in NodeJS itself, it inherited its performance as well. Express 3.x is a light-weight web application framework to help organize your web application into an MVC architecture on the server side. You can then use a database like `MongoDB` with `Mongoose` (for modeling) to provide a backend for your Node.js application. Express.js basically helps you manage everything, from routes, to handling requests and views. It has become the standard server framework for node.js. Express is the backend part of something known as the MEAN stack. The MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications which has the following components; 1. **MongoDB** - The standard NoSQL database 2. **Express.js** - The default web applications framework 3. **Angular.js** - The JavaScript MVC framework used for web applications 4. **Node.js** - Framework used for scalable server-side and networking applications. The Express.js framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests. **using Express** ```javascript var express=require('express'); var app=express(); app.get('/',function(req,res) { res.send('Hello World!'); }); var server=app.listen(3000,function() {}); ``` <div align="right"> <b><a href="#">↥ back to top</a></b> </div> ## Q. ***Explain the terms body-parser, cookie-parser, morgan, nodemon, cors, dotenv, moment in Express JS?*** **a) body-parser** `body-parser` extract the entire body portion of an incoming request stream and exposes it on `req.body`. This body-parser module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST request. ```javascript== // server.js var express = require('express') var bodyParser = require('body-parser') var app = express() // create application/json parser var jsonParser = bodyParser.json() // create application/x-www-form-urlencoded parser var urlencodedParser = bodyParser.urlencoded({ extended: false }) // POST /login gets urlencoded bodies app.post('/login', urlencodedParser, function (req, res) { res.send('welcome, ' + req.body.username) }) // POST /api/users gets JSON bodies app.post('/api/users', jsonParser, function (req, res) { // create user in req.body }) ``` **b) cookie-parser** A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using. The `cookie-parser` middleware\'s cookieParser function takes a `secret` string or array of strings as the first argument and an `options` object as the second argument. *Example*: ```javascript= var express = require('express') var cookieParser = require('cookie-parser') var app = express() app.use(cookieParser()) app.get('/', function (req, res) { // Cookies that have not been signed console.log('Cookies: ', req.cookies) // Cookies that have been signed console.log('Signed Cookies: ', req.signedCookies) }) app.listen(3000) ``` **c) morgan** HTTP request logger middleware for node.js. *Example*: write logs to a file ```javascript= var express = require('express') var fs = require('fs') var morgan = require('morgan') var path = require('path') var app = express() // create a write stream (in append mode) var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) // setup the logger app.use(morgan('combined', { stream: accessLogStream })) app.get('/', function (req, res) { res.send('hello, world!') }) ``` **d) nodemon** Nodemon is a utility that will monitor for any changes in source and automatically restart your server. *Example*: ```javascript= { // ... "scripts": { "start": "nodemon server.js" }, // ... } ``` **g) cors** **C**ross-**O**rigin **R**esource **S**haring (CORS) headers allow apps running in the browser to make requests to servers on different domains (also known as origins). CORS headers are set on the server side - the HTTP server is responsible for indicating that a given HTTP request can be cross-origin. CORS defines a way in which a browser and server can interact and determine whether or not it is safe to allow a cross-origin request. **Example: Enable All CORS Requests** ```javascript= var express = require('express') var cors = require('cors') var app = express() app.use(cors()) app.get('/products/:id', function (req, res, next) { res.json({msg: 'This is CORS-enabled for all origins!'}) }) app.listen(8080, function () { console.log('CORS-enabled web server listening on port 80') }) ``` **Example: Enable CORS for a Single Route** ```javascript= var express = require('express') var cors = require('cors') var app = express() app.get('/products/:id', cors(), function (req, res, next) { res.json({msg: 'This is CORS-enabled for a Single Route'}) }) app.listen(8080, function () { console.log('CORS-enabled web server listening on port 80') }) ``` **h) dotenv** When a NodeJs application runs, it injects a global variable called `process.env` which contains information about the state of environment in which the application is running. The `dotenv` loads environment variables stored in the `.env` file into `process.env`. **Usage** ```javascript= // .env DB_HOST=localhost DB_USER=admin DB_PASS=root ``` ```javascript= // config.js const db = require('db') db.connect({ host: process.env.DB_HOST, username: process.env.DB_USER, password: process.env.DB_PASS }) ``` **j) moment** A JavaScript date library for parsing, validating, manipulating, and formatting dates. **Usage**: Read more [here](https://momentjs.com/) <div align="right"> <b><a href="#">↥ back to top</a></b> </div>