{"id":13459055,"url":"https://github.com/learning-zone/nodejs-basics","last_synced_at":"2025-05-14T15:02:50.598Z","repository":{"id":37386253,"uuid":"192476541","full_name":"learning-zone/nodejs-basics","owner":"learning-zone","description":"Node.js Basics ( v18.x )","archived":false,"fork":false,"pushed_at":"2024-12-27T16:10:49.000Z","size":3698,"stargazers_count":3098,"open_issues_count":0,"forks_count":1038,"subscribers_count":51,"default_branch":"master","last_synced_at":"2025-04-11T05:12:22.777Z","etag":null,"topics":["callback-functions","callback-hell","event-driven-programming","nodejs","nodejs-interview-questions","rest-api"],"latest_commit_sha":null,"homepage":"https://learning-zone.github.io/nodejs-basics/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/learning-zone.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-06-18T06:09:52.000Z","updated_at":"2025-04-10T19:15:55.000Z","dependencies_parsed_at":"2023-01-30T23:31:28.913Z","dependency_job_id":"2fb8031f-ab2b-4bd5-9ff6-34960685803f","html_url":"https://github.com/learning-zone/nodejs-basics","commit_stats":null,"previous_names":["learning-zone/nodejs-interview-questions"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fnodejs-basics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fnodejs-basics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fnodejs-basics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fnodejs-basics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learning-zone","download_url":"https://codeload.github.com/learning-zone/nodejs-basics/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248345267,"owners_count":21088244,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["callback-functions","callback-hell","event-driven-programming","nodejs","nodejs-interview-questions","rest-api"],"created_at":"2024-07-31T09:01:01.927Z","updated_at":"2025-04-11T05:12:28.468Z","avatar_url":"https://github.com/learning-zone.png","language":"JavaScript","readme":"# Node.js Basics\n\n\u003e *Click \u0026#9733; if you like the project. Your contributions are heartily ♡ welcome.*\n\n\u003cbr/\u003e\n\n## Related Topics\n\n* *[HTML Basics](https://github.com/learning-zone/html-basics)*\n* *[CSS Basics](https://github.com/learning-zone/css-basics)*\n* *[JavaScript Basics](https://github.com/learning-zone/javascript-basics)*\n* *[SQL Basics](https://github.com/learning-zone/sql-basics)*\n* *[MongoDB Basics](https://github.com/learning-zone/mongodb-basics)*\n* *[Node.js APIs](nodejs-api.md)*\n* *[Node.js Commands](nodejs-commands.md)*\n* *[Node.js Coding Practice](nodejs-programming.md)*\n\n\u003cbr/\u003e\n\n## Table of Contents\n\n* [Introduction](#-1-introduction)\n* [Node.js Setup](#-2-nodejs-setup)\n* [Node.js Data Types](#-3-nodejs-data-types)\n* [Node.js Architecture](#-4-nodejs-architecture)\n* [Node.js Events](#-5-nodejs-events)\n* [Node.js File System](#-6-nodejs-file-system)\n* [Node.js Streams](#-7-nodejs-streams)\n* [Node.js Multithreading](#-8-nodejs-multithreading)\n* [Node.js Web Module](#-9-nodejs-web-module)\n* [Node.js Middleware](#-10-nodejs-middleware)\n* [Node.js RESTFul API](#-11-nodejs-restful-api)\n* [Node.js Routing](#-12-nodejs-routing)\n* [Node.js Caching](#-13-nodejs-caching)\n* [Node.js Error Handling](#-14-nodejs-error-handling)\n* [Node.js Logging](#-15-nodejs-logging)\n* [Node.js Internationalization](#-16-nodejs-internationalization)\n* [Node.js Testing](#-17-nodejs-testing)\n* [Node.js Miscellaneous](#-18-nodejs-miscellaneous)\n\n\u003cbr/\u003e\n\n## # 1. INTRODUCTION\n\n\u003cbr/\u003e\n\n## Q. What is Node.js?\n\nNode.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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Node.js Process Model?\n\nNode.js runs in a single process and the application code runs in a single thread and thereby needs less resources than other platforms.\n\nAll 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the key features of Node.js?\n\n* **Asynchronous and Event driven** – All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus it will not wait for the response from the previous requests.\n\n* **Fast in Code execution** – Node.js 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 processing of requests within Node.js also become faster.\n\n* **Single Threaded but Highly Scalable** – Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately. However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single thread that provides service to much larger numbers of such requests.\n\n* **Node.js library uses JavaScript** – This is another important aspect of Node.js from the developer\\'s point of view. The majority of developers are already well-versed in JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.\n\n* **There is an Active and vibrant community for the Node.js framework** – The active community always keeps the framework updated with the latest trends in the web development.\n\n* **No Buffering** – Node.js applications never buffer any data. They simply output the data in chunks.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How does Node.js work?\n\nA 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.\n\nNode.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.\n\nWhile 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between process and threads in Node.js?\n\n**1. Process:**\n\nProcesses are basically the programs that are dispatched from the ready state and are scheduled in the CPU for execution. PCB (Process Control Block) holds the concept of process. A process can create other processes which are known as Child Processes. The process takes more time to terminate and it is isolated means it does not share the memory with any other process.\n\nThe process can have the following states new, ready, running, waiting, terminated, and suspended.\n\n**2. Thread:**\n\nThread is the segment of a process which means a process can have multiple threads and these multiple threads are contained within a process. A thread has three states: Running, Ready, and Blocked.\n\nThe thread takes less time to terminate as compared to the process but unlike the process, threads do not isolate.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 2. NODE.JS SETUP\n\n\u003cbr/\u003e\n\n## Q. How to create a simple server in Node.js that returns Hello World?\n\n**Step 01**: Create a project directory\n\n```js\nmkdir myapp\ncd myapp\n```\n\n**Step 02**: Initialize project and link it to npm\n\n```js\nnpm init\n```\n\nThis creates a `package.json` file in your myapp folder. The file contains references for all npm packages you have downloaded to your project. The command will prompt you to enter a number of things.\nYou can enter your way through all of them EXCEPT this one:\n\n```js\nentry point: (index.js)\n```\n\nRename this to:\n\n```js\napp.js\n```\n\n**Step 03**: Install Express in the myapp directory\n\n```js\nnpm install express --save\n```\n\n**Step 04**: app.js\n\n```js\n/**\n * Express.js\n */\nconst express = require('express');\nconst app = express();\n\napp.get('/', function (req, res) {\n  res.send('Hello World!');\n});\n\napp.listen(3000, function () {\n  console.log('App listening on port 3000!');\n});\n```\n\n**Step 05**: Run the app\n\n```bah\nnode app.js\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/hello-world-in-nodejs-ue3cs3)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain the concept of URL module in Node.js?\n\nThe URL module in Node.js splits up a web address into readable parts. Use `require()` to include the module. Then parse an address with the `url.parse()` method, and it will return a URL object with each part of the address as properties.\n\n**Example:**\n\n```js\n/**\n * URL Module in Node.js\n */\nconst url = require('url');\nconst adr = 'http://localhost:8080/default.htm?year=2022\u0026month=september';\nconst q = url.parse(adr, true);\n\nconsole.log(q.host); // localhost:8080\nconsole.log(q.pathname); // \"/default.htm\"\nconsole.log(q.search); // \"?year=2022\u0026month=september\"\n\nconst qdata = q.query; // { year: 2022, month: 'september' }\nconsole.log(qdata.month); // \"september\"\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 3. NODE.JS DATA TYPES\n\n\u003cbr/\u003e\n\n## Q. What are the data types in Node.js?\n\nJust like JS, there are two categories of data types in Node: Primitives and Objects.\n\n**1. Primitives:**\n\n* String\n* Number\n* BigInt\n* Boolean\n* Undefined\n* Null\n* Symbol\n\n**2. Objects:**\n\n* Function\n* Array\n* Buffer\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain String data type in Node.js?\n\nStrings in Node.js are sequences of unicode characters. Strings can be wrapped in a single or double quotation marks.\nJavascript provide many functions to operate on string, like indexOf(), split(), substr(), length.\n\n**String functions:**\n\n|Function   | Description               |\n|-----------|---------------------------|\n|charAt()   |It is useful to find a specific character present in a string.|\n|concat()   |It is useful to concat more than one string.|\n|indexOf()  |It is useful to get the index of a specified character or a part of the string.|\n|match()    |It is useful to match multiple strings.|\n|split()    |It is useful to split the string and return an array of string.|\n|join()     |It is useful to join the array of strings and those are separated by comma (,) operator.|\n\n**Example:**\n\n```js\n/** \n * String Data Type\n */\nconst str1 = \"Hello\";\nconst str2 = 'World';\n\nconsole.log(\"Concat Using (+) :\" , (str1 + ' ' + str2));\nconsole.log(\"Concat Using Function :\" , (str1.concat(str2)));\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain Number data type in Node.js?\n\nThe number data type in Node.js is 64 bits floating point number both positive and negative. The parseInt() and parseFloat() functions are used to convert to number, if it fails to convert into a number then it returns `NaN`.\n\n**Example:**\n\n```js\n/**\n * Number Data Type\n */\n// Example 01:\nconst num1 = 10;\nconst num2 = 20;\n\nconsole.log(`sum: ${num1 + num2}`); \n\n// Example 02:\nconsole.log(parseInt(\"32\"));  // 32\nconsole.log(parseFloat(\"8.24\")); // 8.24\nconsole.log(parseInt(\"234.12345\")); // 234\nconsole.log(parseFloat(\"10\")); // 10\n\n// Example 03:\nconsole.log(isFinite(10/5)); // true\nconsole.log(isFinite(10/0)); // false\n\n// Example 04:\nconsole.log(5 / 0); // Infinity\nconsole.log(-5 / 0); // -Infinity\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain BigInt data type in Node.js?\n\nA BigInt value, also sometimes just called a BigInt, is a bigint primitive, created by appending **n** to the end of an integer literal, or by calling the BigInt() function ( without the new operator ) and giving it an integer value or string value.\n\n**Example:**\n\n```js\n/**\n * BigInt Data Type\n */\nconst maxSafeInteger = 99n; // This is a BigInt\nconst num2 = BigInt('99'); // This is equivalent\nconst num3 = BigInt(99); // Also works\n\ntypeof 1n === 'bigint'           // true\ntypeof BigInt('1') === 'bigint'  // true\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain Boolean data type in Node.js?\n\nBoolean data type is a data type that has one of two possible values, either true or false. In programming, it is used in logical representation or to control program structure.\n\nThe boolean() function is used to convert any data type to a boolean value. According to the rules, false, 0, NaN, null, undefined, empty string evaluate to false and other values evaluates to true.\n\n**Example:**\n\n```js\n/**\n * Boolean Data Type\n */\n// Example 01:\nconst isValid = true; \nconsole.log(isValid); // true \n\n// Example 02:\nconsole.log(true \u0026\u0026 true); // true \nconsole.log(true \u0026\u0026 false); // false \nconsole.log(true || false); // true \nconsole.log(false || false); // false \nconsole.log(!true); // false \nconsole.log(!false); // true \n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain `Undefined` and `Null` data type in Node.js?\n\nIn node.js, if a variable is defined without assigning any value, then that will take **undefined** as value. If we assign a null value to the variable, then the value of the variable becomes **null**.\n\n**Example:**\n\n```js\n/**\n * NULL and UNDEFINED Data Type\n */\nlet x;\nconsole.log(x); // undefined\n\nlet y = null;\nconsole.log(y); // null\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain Symbol data type in Node.js?\n\nSymbol is an immutable primitive value that is unique. It\\'s a very peculiar data type. Once you create a symbol, its value is kept private and for internal use.\n\n**Example:**\n\n```js\n/**\n * Symbol Data Type\n */\nconst NAME = Symbol()\nconst person = {\n  [NAME]: 'Ritika Bhavsar'\n}\n\nperson[NAME] // 'Ritika Bhavsar'\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain function in Node.js?\n\nFunctions are first class citizens in Node\\'s JavaScript, similar to the browser\\'s JavaScript. A function can have attributes and properties also. It can be treated like a class in JavaScript.\n\n**Example:**\n\n```js\n/**\n * Function in Node.js\n */\nfunction Messsage(name) {\n console.log(\"Hello \"+name);\n}\n\nMesssage(\"World\"); // Hello World\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain Buffer data type in Node.js?\n\nNode.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.\n\n**Example:**\n\n```js\n/**\n * Buffer Data Type\n */\nlet b = new Buffer(10000);\nlet str = \"----------\";\n\nb.write(str); \nconsole.log( str.length ); // 10\nconsole.log( b.length ); // 10000\n```\n\n*Note: Buffer() is deprecated due to security and usability issues.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4. NODE.JS ARCHITECTURE\n\n\u003cbr/\u003e\n\n## Q. How does Node.js works?\n\nNode.js is completely event-driven. Basically the server consists of one thread processing one event after another.\n\nA 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.\n\nNode.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.  \n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/event-loop.png\" alt=\"Node Architecture\" width=\"800px\" /\u003e\n\u003c/p\u003e\n  \n**Single Threaded Event Loop Model Processing Steps:**\n\n* Clients Send request to Web Server.\n* Node.js Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.\n* Node.js Web Server receives those requests and places them into a Queue. It is known as **Event Queue**.\n* 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.\n* Event Loop uses Single Thread only. It is main heart of Node.js Platform Processing Model.\n* Event Loop checks any Client Request is placed in Event Queue. If no, then wait for incoming requests for indefinitely.\n* If yes, then pick up one Client Request from Event Queue\n    * Starts process that Client Request\n    * If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client.\n    * If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach\n        * Checks Threads availability from Internal Thread Pool\n        * Picks up one Thread and assign this Client Request to that thread.\n        * That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop\n        * Event Loop in turn, sends that Response to the respective Client.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the core modules of Node.js?\n\nNode.js has a set of core modules that are part of the platform and come with the Node.js installation. These modules can be loaded into the program by using the require function.\n\n**Syntax:**\n\n```js\nconst module = require('module_name');\n```\n\n**Example:**\n\n```js\nconst http = require('http');\n\nhttp.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/html'});\n  res.write('Welcome to Node.js!');\n  res.end();\n}).listen(3000);\n```\n\nThe following table lists some of the important core modules in Node.js.\n\n|Name         |Description                                             |\n|-------------|--------------------------------------------------------|\n|Assert       |It is used by Node.js for testing itself. It can be accessed with require('assert').|\n|Buffer       |It is used to perform operations on raw bytes of data which reside in memory. It can be accessed with require('buffer')|\n|Child Process|It is used by node.js for managing child processes. It can be accessed with require('child_process').|\n|Cluster      |This module is used by Node.js to take advantage of multi-core systems, so that it can handle more load. It can be accessed with require('cluster').|\n|Console      |It is used to write data to console. Node.js has a Console object which contains functions to write data to console. It can be accessed with require('console'). |\n|Crypto       |It is used to support cryptography for encryption and decryption. It can be accessed with require('crypto').|\n|HTTP         |It includes classes, methods and events to create Node.js http server.|\n|URL          |It includes methods for URL resolution and parsing.|\n|Query String |It includes methods to deal with query string.|\n|Path         |It includes methods to deal with file paths.|\n|File System  |It includes classes, methods, and events to work with file I/O.|\n|Util         |It includes utility functions useful for programmers.|\n|Zlib         |It is used to compress and decompress data. It can be accessed with require('zlib').|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What do you understand by Reactor Pattern in Node.js?\n\n**Reactor Pattern** is used to avoid the blocking of the Input/Output operations. It provides us with a handler that is associated with I/O operations. When the I/O requests are to be generated, they get submitted to a demultiplexer, which handles concurrency in avoiding the blocking of the I/O mode and collects the requests in form of an event and queues those events.\n\n**There are two ways in which I/O operations are performed:**\n\n**1. Blocking I/O:** Application will make a function call and pause its execution at a point until the data is received. It is called as \"Synchronous\".\n\n**2. Non-Blocking I/O:** Application will make a function call, and, without waiting for the results it continues its execution. It is called as \"Asynchronous\".\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"/assets/reactor-pattern.jpg\" alt=\"Reactor Pattern\" width=\"600px\" /\u003e\n\u003c/p\u003e\n\n**Reactor Pattern comprises of:**\n\n**1. Resources:** They are shared by multiple applications for I/O operations, generally slower in executions.\n\n**2. Synchronous Event De-multiplexer/Event Notifier:** This uses Event Loop for blocking on all resources. When a set of I/O operations completes, the Event De-multiplexer pushes the new events into the Event Queue.\n\n**3. Event Loop and Event Queue:** Event Queue queues up the new events that occurred along with its event-handler, pair.\n\n**4. Request Handler/Application:** This is, generally, the application that provides the handler to be executed for registered events on resources.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the global objects of Node.js?\n\nNode.js Global Objects are the objects that are available in all modules. Global Objects are built-in objects that are part of the JavaScript and can be used directly in the application without importing any particular module.\n\nThese objects are modules, functions, strings and object itself as explained below.\n\n**1. global:**\n\nIt is a global namespace. Defining a variable within this namespace makes it globally accessible.\n\n```js\nvar myvar;\n```\n\n**2. process:**\n\nIt is an inbuilt global object that is an instance of EventEmitter used to get information on current process. It can also be accessed using require() explicitly.\n\n**3. console:**\n\nIt is an inbuilt global object used to print to stdout and stderr.\n\n```js\nconsole.log(\"Hello World\"); // Hello World\n```\n\n**4. setTimeout(), clearTimeout(), setInterval(), clearInterval():**\n\nThe built-in timer functions are globals\n\n```js\nfunction printHello() {\n   console.log( \"Hello, World!\");\n}\n\n// Now call above function after 2 seconds\nvar timeoutObj = setTimeout(printHello, 2000);\n```\n\n**5. __dirname:**\n\nIt is a string. It specifies the name of the directory that currently contains the code.\n\n```js\nconsole.log(__dirname);\n```\n\n**6. __filename:**\n\nIt specifies the filename of the code being executed. This is the resolved absolute path of this code file. The value inside a module is the path to that module file.\n\n```js\nconsole.log(__filename);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is chrome v8 engine?\n\nV8 is a C++ based open-source JavaScript engine developed by Google. It was originally designed for Google Chrome and Chromium-based browsers ( such as Brave ) in 2008, but it was later utilized to create Node.js for server-side coding.\n\nV8 is the JavaScript engine i.e. it parses and executes JavaScript code. The DOM, and the other Web Platform APIs ( they all makeup runtime environment ) are provided by the browser.\n\nV8 is known to be a JavaScript engine because it takes JavaScript code and executes it while browsing in Chrome. It provides a runtime environment for the execution of JavaScript code. The best part is that the JavaScript engine is completely independent of the browser in which it runs.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why is LIBUV needed in Node JS?\n\n**libuv** is a C library originally written for Node.js to abstract non-blocking I/O operations. It provides the following features:\n\n* It allows the CPU and other resources to be used simultaneously while still performing I/O operations, thereby resulting in efficient use of resources and network.\n* It facilitates an event-driven approach wherein I/O and other activities are performed using callback-based notifications.\n* It provides mechanisms to handle file system, DNS, network, child processes, pipes, signal handling, polling and streaming\n* It also includes a thread pool for offloading work for some things that can\\'t be done asynchronously at the operating system level.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How V8 compiles JavaScript code?\n\nCompilation is the process of converting human-readable code to machine code. There are two ways to compile the code\n\n* **Using an Interpreter**: The interpreter scans the code line by line and converts it into byte code.\n* **Using a Compiler**: The Compiler scans the entire document and compiles it into highly optimized byte code.\n\nThe V8 engine uses both a compiler and an interpreter and follows **just-in-time (JIT)** compilation to speed up the execution. JIT compiling works by compiling small portions of code that are just about to be executed. This prevents long compilation time and the code being compiles is only that which is highly likely to run.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 5. NODE.JS EVENTS\n\n\u003cbr/\u003e\n\n## Q. What is EventEmitter in Node.js?\n\nThe EventEmitter is a class that facilitates communication/interaction between objects in Node.js. The EventEmitter class can be used to create and handle custom events.\n\nEventEmitter is at the core of Node asynchronous event-driven architecture. Many of Node\\'s built-in modules inherit from EventEmitter including prominent frameworks like Express.js. An emitter object basically has two main features:\n\n* Emitting name events.\n* Registering and unregistering listener functions.\n\n**Example:**\n\n```js\n/**\n * Callback Events with Parameters\n */\nconst events = require('events');\nconst eventEmitter = new events.EventEmitter();\n\nfunction listener(code, msg) {\n   console.log(`status ${code} and ${msg}`);\n}\n\neventEmitter.on('status', listener); // Register listener\neventEmitter.emit('status', 200, 'ok');\n\n// Output\nstatus 200 and ok\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How does the EventEmitter works in Node.js?\n\n* Event Emitter emits the data in an event called message\n* A Listened is registered on the event message\n* when the message event emits some data, the listener will get the data\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/eventEmitter_works.png\" alt=\"EventEmitter\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\n**Building Blocks:**\n\n* **.emit()** - this method in event emitter is to emit an event in module\n* **.on()** - this method is to listen to data on a registered event in node.js\n* **.once()** - it listen to data on a registered event only once.\n* **.addListener()** - it checks if the listener is registered for an event.\n* **.removeListener()** - it removes the listener for an event.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/eventemiitter.png\" alt=\"Building Blocks\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\n**Example 01:**\n\n```js\n/**\n * Callbacks Events\n */\nconst events = require('events');\nconst eventEmitter = new events.EventEmitter();\n\nfunction listenerOne() {\n   console.log('First Listener Executed');\n}\n\nfunction listenerTwo() {\n   console.log('Second Listener Executed');\n}\n\neventEmitter.on('listenerOne', listenerOne); // Register for listenerOne\neventEmitter.on('listenerOne', listenerTwo); // Register for listenerOne\n\n// When the event \"listenerOne\" is emitted, both the above callbacks should be invoked.\neventEmitter.emit('listenerOne');\n\n// Output\nFirst Listener Executed\nSecond Listener Executed\n```\n\n**Example 02:**\n\n```js\n/**\n * Emit Events Once\n */\nconst events = require('events');\nconst eventEmitter = new events.EventEmitter();\n\nfunction listenerOnce() {\n   console.log('listenerOnce fired once');\n}\n\neventEmitter.once('listenerOne', listenerOnce); // Register listenerOnce\neventEmitter.emit('listenerOne');\n\n// Output\nlistenerOnce fired once\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the EventEmitter methods available in Node.js?\n\n|EventEmitter Methods | Description         |\n|---------------------|---------------------|\n|.addListener(event, listener) |Adds a listener to the end of the listeners array for the specified event.|\n|.on(event, listener) |Adds a listener to the end of the listeners array for the specified event. It can also be called as an alias of emitter.addListener()|\n|.once(event, listener)|This listener is invoked only the next time the event is fired, after which it is removed.|\n|.removeListener(event, listener)|Removes a listener from the listener array for the specified event.|\n|.removeAllListeners([event])|Removes all listeners, or those of the specified event.|\n|.setMaxListeners(n)  |By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.|\n|.getMaxListeners()   |Returns the current maximum listener value for the emitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.|\n|.listeners(event)    |Returns a copy of the array of listeners for the specified event.|\n|.emit(event[, arg1][, arg2][, ...]) |Raise the specified events with the supplied arguments.|\n|.listenerCount(type) |Returns the number of listeners listening to the type of event.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How the Event Loop Works in Node.js?\n\nThe **event loop** allows Node.js to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. It is done by offloading operations to the system kernel whenever possible.\n\nNode.js is a single-threaded application, but it can support **concurrency** via the concept of **event** and **callbacks**. Every API of Node.js is asynchronous and being single-threaded, they use **async function calls** to maintain concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute.\n\n**Features of Event Loop:**\n\n* Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks.\n* The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task.\n* The event loop allows us to use callbacks and promises.\n* The event loop executes the tasks starting from the oldest first.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/nodejs-event-loop.png\" alt=\"Event Loop\" width=\"600px\" /\u003e\n\u003c/p\u003e\n\n**Example:**\n\n```js\n/**\n * Event loop in Node.js\n */\nconst events = require('events');\nconst eventEmitter = new events.EventEmitter();\n\n// Create an event handler as follows\nconst connectHandler = function connected() {\n   console.log('connection succesful.');\n   eventEmitter.emit('data_received');\n}\n\n// Bind the connection event with the handler\neventEmitter.on('connection', connectHandler);\n \n// Bind the data_received event with the anonymous function\neventEmitter.on('data_received', function() {\n   console.log('data received succesfully.');\n});\n\n// Fire the connection event \neventEmitter.emit('connection');\nconsole.log(\"Program Ended.\");\n\n// Output\nConnection succesful.\nData received succesfully.\nProgram Ended.\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How are event listeners created in Node.JS?\n\nAn array containing all eventListeners is maintained by Node. Each time **.on()** function is executed, a new event listener is added to that array. When the concerned event is emitted, each **eventListener** that is present in the array is called in a sequential or synchronous manner.\n\nThe event listeners are called in a synchronous manner to avoid logical errors, race conditions etc. The total number of listeners that can be registered for a particular event, is controlled by **.setMaxListeners(n)**. The default number of listeners is 10.\n\n```js\nemitter.setMaxlisteners(12);\n```\n\nAs an event Listener once registered, exists throughout the life cycle of the program. It is important to detach an event Listener once its no longer needed to avoid memory leaks. Functions like **.removeListener()**, **.removeAllListeners()** enable the removal of listeners from the listeners Array.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between process.nextTick() and setImmediate()?\n\n**1. process.nextTick():**\n\nThe process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed.\n\n**2. setImmediate():**\n\nThe setImmediate() method is used to execute a function right after the current event loop finishes. It is callback function is placed in the check phase of the next event queue.\n\n**Example:**\n\n```js\n/**\n * setImmediate() and process.nextTick()\n */\nsetImmediate(() =\u003e {\n  console.log(\"1st Immediate\");\n});\n\nsetImmediate(() =\u003e {\n  console.log(\"2nd Immediate\");\n});\n\nprocess.nextTick(() =\u003e {\n  console.log(\"1st Process\");\n});\n\nprocess.nextTick(() =\u003e {\n  console.log(\"2nd Process\");\n});\n\n// First event queue ends here\nconsole.log(\"Program Started\");\n\n// Output\nProgram Started\n1st Process\n2nd Process\n1st Immediate\n2nd Immediate\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is callback function in Node.js?\n\nA callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime.\n\nCallback is called when task get completed and is asynchronous equivalent for a function. Using Callback concept, Node.js can process a large number of requests without waiting for any function to return the result which makes Node.js highly scalable.\n\n**Example:**\n\n```js\n/**\n * Callback Function\n */\nfunction message(name, callback) {\n  console.log(\"Hi\" + \" \" + name);\n  callback();\n}\n\n// Callback function\nfunction callMe() {\n  console.log(\"I am callback function\");\n}\n\n// Passing function as an argument\nmessage(\"Node.JS\", callMe);\n```\n\n**Output:**\n\n```js\nHi Node.JS\nI am callback function\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the difference between Events and Callbacks?\n\n**1. Events:**\n\nNode.js **events** module which emits named events that can cause corresponding functions or callbacks to be called. Functions ( callbacks ) listen or subscribe to a particular event to occur and when that event triggers, all the callbacks subscribed to that event are fired one by one in order to which they were registered.\n\nAll objects that emit events are instances of the **EventEmitter** class. The event can be emitted or listen to an event with the help of EventEmitter\n\n**Example:**\n\n```js\n/**\n * Events Module\n */\nconst event = require('events');  \nconst eventEmitter = new event.EventEmitter();  \n  \n// add listener function for Sum event  \neventEmitter.on('Sum', function(num1, num2) {  \n    console.log('Total: ' + (num1 + num2));  \n});  \n\n// call event  \neventEmitter.emit('Sum', 10, 20);\n\n// Output\nTotal: 30\n```\n\n**2. Callbacks:**\n\nA callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.\n\n**Example:**\n\n```js\n/**\n * Callbacks\n */\nfunction sum(number) {\n  console.log('Total: ' + number);\n}\n\nfunction calculator(num1, num2, callback) {\n  let total = num1 + num2;\n  callback(total);\n}\n\ncalculator(10, 20, sum);\n\n// Output\nTotal: 30\n```\n\nCallback functions are called when an asynchronous function returns its result, whereas event handling works on the **observer pattern**. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is an error-first callback?\n\nThe pattern used across all the asynchronous methods in Node.js is called *Error-first Callback*. Here is an example:\n\n```js\nfs.readFile( \"file.json\", function ( err, data ) {\n  if ( err ) {\n    console.error( err );\n  }\n  console.log( data );\n});\n```\n\nAny asynchronous method expects one of the arguments to be a callback. The full callback argument list depends on the caller method, but the first argument is always an error object or null. When we go for the asynchronous method, an exception thrown during function execution cannot be detected in a try/catch statement. The event happens after the JavaScript engine leaves the try block.\n\nIn the preceding example, if any exception is thrown during the reading of the file, it lands on the callback function as the first and mandatory parameter.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is callback hell in Node.js?\n\nThe 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.\n\nAn 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.\n\n**Example:**\n\n```js\n/**\n * Callback Hell\n */\nfirstFunction(function (a) {\n  secondFunction(a, function (b) {\n    thirdFunction(b, function (c) {\n      // And so on…\n    });\n  });\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to avoid callback hell in Node.js?\n\n**1. Managing callbacks using Async.js:**  \n\n`Async` is a really powerful npm module for managing asynchronous nature of JavaScript. Along with Node.js, it also works for JavaScript written for browsers.\n\nAsync provides lots of powerful utilities to work with asynchronous processes under different scenarios.\n\n```js\nnpm install --save async\n```\n\n**2. Managing callbacks hell using promises:**  \n\nPromises are alternative to callbacks while dealing with asynchronous code. Promises return the value of the result or an error exception. The core of the promises is the `.then()` function, which waits for the promise object to be returned.\n\nThe `.then()` function takes two optional functions as arguments and depending on the state of the promise only one will ever be called. The first function is called when the promise if fulfilled (A successful result). The second function is called when the promise is rejected.\n\n**Example:**\n\n```js\n/**\n * Promises\n */\nconst myPromise = new Promise((resolve, reject) =\u003e {\n  setTimeout(() =\u003e {\n    resolve(\"Successful!\");\n  }, 300);\n});\n```\n\n**3. Using Async Await:**  \n\nAsync await makes asynchronous code look like it\\'s synchronous. This has only been possible because of the reintroduction of promises into node.js. Async-Await only works with functions that return a promise.\n\n**Example:**\n\n```js\n/**\n * Async Await\n */\nconst getrandomnumber = function(){\n    return new Promise((resolve, reject)=\u003e{\n        setTimeout(() =\u003e {\n            resolve(Math.floor(Math.random() * 20));\n        }, 1000);\n    });\n}\n\nconst addRandomNumber = async function(){\n    const sum = await getrandomnumber() + await getrandomnumber();\n    console.log(sum);\n}\n\naddRandomNumber();\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is typically the first argument passed to a callback handler?\n\nThe first parameter of the callback is the **error** value. If the function hits an error, then they typically call the **callback** with the first parameter being an Error object.\n\n**Example:**\n\n```js\n/**\n * Callback Handler\n */\nconst Division = (numerator, denominator, callback) =\u003e {\n    if (denominator === 0) {\n      callback(new Error('Divide by zero error!'));\n    } else {\n      callback(null, numerator / denominator);\n    }\n};\n\n// Function Call\nDivision(5, 0, (err, result) =\u003e {\n  if (err) {\n    return console.log(err.message);\n  }\n  console.log(`Result: ${result}`);\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the timing features of Node.js?\n\nThe Timers module in Node.js contains functions that execute code after a set period of time. Timers do not need to be imported via require(), since all the methods are available globally to emulate the browser JavaScript API.\n\nSome of the functions provided in this module are\n\n**1. setTimeout():**\n\nThis function schedules code execution after the assigned amount of time ( in milliseconds ). Only after the timeout has occurred, the code will be executed. This method returns an ID that can be used in **clearTimeout()** method.\n\n**Syntax:**\n\n```js\nsetTimeout(callback, delay, args )\n```\n\n**Example:**\n\n```js\nfunction printMessage(arg) {\n  console.log(`${arg}`);\n}\n\nsetTimeout(printMessage, 1000, 'Display this Message after 1 seconds!');\n```\n\n**2. setImmediate():**\n\nThe setImmediate() method executes the code at the end of the current event loop cycle. The function passed in the setImmediate() argument is a function that will be executed in the next iteration of the event loop.\n\n**Syntax:**\n\n```js\nsetImmediate(callback, args)\n```\n\n**Example:**\n\n```js\n// Setting timeout for the function\nsetTimeout(function () {\n    console.log('setTimeout() function running...');\n}, 500);\n\n// Running this function immediately before any other\nsetImmediate(function () {\n   console.log('setImmediate() function running...');\n});\n\n// Directly printing the statement\nconsole.log('Normal statement in the event loop');\n\n// Output\n// Normal statement in the event loop\n// setImmediate() function running...\n// setTimeout() function running...\n```\n\n**3. setInterval():**\n\nThe setInterval() method executes the code after the specified interval. The function is executed multiple times after the interval has passed. The function will keep on calling until the process is stopped externally or using code after specified time period. The clearInterval() method can be used to prevent the function from running.\n\n**Syntax:**\n\n```js\nsetInterval(callback, delay, args)\n```\n\n**Example:**\n\n```js\nsetInterval(function() {\n    console.log('Display this Message intervals of 1 seconds!');\n}, 1000);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to implement a sleep function in Node.js?\n\nOne way to delay execution of a function in Node.js is to use async/await with promises to delay execution without callbacks function. Just put the code you want to delay in the callback. For example, below is how you can wait 1 second before executing some code.\n\n**Example:**\n\n```js\nfunction delay(time) {\n  return new Promise((resolve) =\u003e setTimeout(resolve, time));\n}\n\nasync function run() {\n  await delay(1000);\n  console.log(\"This printed after about 1 second\");\n}\n\nrun();\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 6. NODE.JS FILE SYSTEM\n\n\u003cbr/\u003e\n\n## Q. How Node.js read the content of a file?\n\nThe \"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 handle several requests in parallel.\n\nCommon use for the File System module:\n\n* Read files\n* Create files\n* Update files\n* Delete files\n* Rename files  \n\n**Example:** Read Files\n\n```html\n\u003c!-- index.html --\u003e\n\u003chtml\u003e\n\u003cbody\u003e\n  \u003ch1\u003eFile Header\u003c/h1\u003e\n  \u003cp\u003eFile Paragraph.\u003c/p\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n```js\n/**\n * read_file.js\n */\nconst http = require('http');\nconst fs = require('fs');\n\nhttp.createServer(function (req, res) {\n  fs.readFile('index.html', function(err, data) {\n    res.writeHead(200, {'Content-Type': 'text/html'});\n    res.write(data);\n    res.end();\n  });\n}).listen(3000);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 7. NODE.JS STREAMS\n\n\u003cbr/\u003e\n\n## Q. How many types of streams are present in node.js?\n\nStreams are objects that let you read data from a source or write data to a destination in continuous fashion.\nThere are four types of streams\n\n* **Readable** − Stream which is used for read operation.\n* **Writable** − Stream which is used for write operation.\n* **Duplex** − Stream which can be used for both read and write operation.\n* **Transform** − A type of duplex stream where the output is computed based on input.  \n\nEach type of Stream is an EventEmitter instance and throws several events at different instance of times.  \n\n**Methods:**\n\n* **data** − This event is fired when there is data is available to read.\n* **end** − This event is fired when there is no more data to read.\n* **error** − This event is fired when there is any error receiving or writing data.\n* **finish** − This event is fired when all the data has been flushed to underlying system.\n\n**1. Reading from a Stream:**\n\n```js\nconst fs = require(\"fs\");\nlet data = \"\";\n\n// Create a readable stream\nconst readerStream = fs.createReadStream(\"file.txt\");\n\n// Set the encoding to be utf8.\nreaderStream.setEncoding(\"UTF8\");\n\n// Handle stream events --\u003e data, end, and error\nreaderStream.on(\"data\", function (chunk) {\n  data += chunk;\n});\n\nreaderStream.on(\"end\", function () {\n  console.log(data);\n});\n\nreaderStream.on(\"error\", function (err) {\n  console.log(err.stack);\n});\n```\n\n**2. Writing to a Stream:**\n\n```js\nconst fs = require(\"fs\");\nconst data = \"File writing to a stream example\";\n\n// Create a writable stream\nconst writerStream = fs.createWriteStream(\"file.txt\");\n\n// Write the data to stream with encoding to be utf8\nwriterStream.write(data, \"UTF8\");\n\n// Mark the end of file\nwriterStream.end();\n\n// Handle stream events --\u003e finish, and error\nwriterStream.on(\"finish\", function () {\n  console.log(\"Write completed.\");\n});\n\nwriterStream.on(\"error\", function (err) {\n  console.log(err.stack);\n});\n```\n\n**3. Piping the Streams:**\n\nPiping is a mechanism where we provide the output of one stream as the input to another stream. It is normally used to get data from one stream and to pass the output of that stream to another stream. There is no limit on piping operations.\n\n```js\nconst fs = require(\"fs\");\n\n// Create a readable stream\nconst readerStream = fs.createReadStream('input.txt');\n\n// Create a writable stream\nconst writerStream = fs.createWriteStream('output.txt');\n\n// Pipe the read and write operations\n// read input.txt and write data to output.txt\nreaderStream.pipe(writerStream);\n```\n\n**4. Chaining the Streams:**\n\nChaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.  \n\n```js\nconst fs = require(\"fs\");\nconst zlib = require('zlib');\n\n// Compress the file input.txt to input.txt.gz\nfs.createReadStream('input.txt')\n   .pipe(zlib.createGzip())\n   .pipe(fs.createWriteStream('input.txt.gz'));\n  \nconsole.log(\"File Compressed.\");\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to handle large data in Node.js?\n\nThe Node.js stream feature makes it possible to process large data continuously in smaller chunks without keeping it all in memory. One benefit of using streams is that it saves time, since you don\\'t have to wait for all the data to load before you start processing. This also makes the process less memory-intensive.\n\nSome of the use cases of Node.js streams include:\n\n* Reading a file that\\'s larger than the free memory space, because it\\'s broken into smaller chunks and processed by streams. For example, a browser processes videos from streaming platforms like Netflix in small chunks, making it possible to watch videos immediately without having to download them all at once.\n\n* Reading large log files and writing selected parts directly to another file without downloading the source file. For example, you can go through traffic records spanning multiple years to extract the busiest day in a given year and save that data to a new file.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 8. NODE.JS MULTITHREADING\n\n\u003cbr/\u003e\n\n## Q. Is Node.js entirely based on a single-thread?\n\nYes, 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.\n\nMoreover, 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.\n\nTo 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How does Node.js handle child threads?\n\nNode.js is a single threaded language which in background uses multiple threads to execute asynchronous code.\nNode.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.\n\n* Nodejs Primary application runs in an event loop, which is in a single thread.\n* 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.\n* Node v11/12 now has experimental worker_threads, which is another option.\n* Node.js does support forking multiple processes ( which are executed on different cores ).\n* It is important to know that state is not shared between master and forked process.\n* We can pass messages to forked process ( which is different script ) and to master process from forked process with function send.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How does Node.js support multi-processor platforms, and does it fully utilize all processor resources?\n\nSince Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port.\n\nThe cluster module helps to spawn new processes on the operating system. Each process works independently, so you cannot use shared state between child processes. Each process communicates with the main process by IPC and pass server handles back and forth.\n\nCluster supports two types of load distribution:\n\n* The main process listens on a port, accepts new connection and assigns it to a child process in a round robin fashion.\n* The main process assigns the port to a child process and child process itself listen the port.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How does the cluster module work in Node.js?\n\nThe cluster module provides a way of creating child processes that runs simultaneously and share the same server port.\n\nNode.js runs single threaded programming, which is very memory efficient, but to take advantage of computers multi-core systems, the Cluster module allows you to easily create child processes that each runs on their own single thread, to handle the load.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/nodejs_cluster.png\" alt=\"Load Balancer\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\n**Example:**\n\n```js\n/**\n * Cluster Module\n */\nconst cluster = require(\"cluster\");\n\nif (cluster.isMaster) {\n  console.log(`Master process is running...`);\n  cluster.fork();\n  cluster.fork();\n} else {\n  console.log(`Worker process started running`);\n}\n```\n\n**Output:**\n\n```js\nMaster process is running...\nWorker process started running\nWorker process started running\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain cluster methods supported by Node.js?\n\n|Method         |Description            |\n|---------------|-----------------------|\n|fork()         |Creates a new worker, from a master|\n|isMaster       |Returns true if the current process is master, otherwise false|\n|isWorker       |Returns true if the current process is worker, otherwise false|\n|id             |A unique id for a worker|\n|process        |Returns the global Child Process|\n|send()         |sends a message to a master or a worker|\n|kill()         |Kills the current worker|\n|isDead         |Returns true if the worker\\'s process is dead, otherwise false|\n|settings       |Returns an object containing the cluster\\'s settings|\n|worker         |Returns the current worker object|\n|workers        |Returns all workers of a master|\n|exitedAfterDisconnect |Returns true if a worker was exited after disconnect, or the kill method|\n|isConnected    |Returns true if the worker is connected to its master, otherwise false|\n|disconnect()   |Disconnects all workers|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to make use of all CPUs in Node.js?\n\nA single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a **cluster** of Node.js processes to handle the load. The cluster module allows easy creation of child processes that all share server ports.\n\nThe cluster module supports two methods of distributing incoming connections.\n\n* The first one (and the default one on all platforms except Windows), is the round-robin approach, where the master process listens on a port, accepts new connections and distributes them across the workers in a round-robin fashion, with some built-in smarts to avoid overloading a worker process.\n\n* The second approach is where the master process creates the listen socket and sends it to interested workers. The workers then accept incoming connections directly.\n\n**Example:**\n\n```js\n/**\n * Server Load Balancing in Node.js\n */\nconst cluster = require(\"cluster\");\nconst express = require(\"express\");\nconst os = require(\"os\");\n\nif (cluster.isMaster) {\n  console.log(`Master PID ${process.pid} is running`);\n\n  // Get the number of available cpu cores\n  const nCPUs = os.cpus().length;\n  // Fork worker processes for each available CPU core\n  for (let i = 0; i \u003c nCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on(\"exit\", (worker, code, signal) =\u003e {\n    console.log(`Worker PID ${worker.process.pid} died`);\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case it is an Express server\n  const app = express();\n  app.get(\"/\", (req, res) =\u003e {\n    res.send(\"Node is Running...\");\n  });\n\n  app.listen(3000, () =\u003e {\n    console.log(`App listening at http://localhost:3000/`);\n  });\n\n  console.log(`Worker PID ${process.pid} started`);\n}\n```\n\nRunning Node.js will now share port 3000 between the workers:\n\n**Output:**\n\n```js\nMaster PID 13972 is running\nWorker PID 5680 started\nApp listening at http://localhost:3000/\nWorker PID 14796 started\n...\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. If Node.js is single threaded then how it handles concurrency?\n\nNode 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.\n\nAs 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.  \n\n**Example:**\n\n```js\n/**\n * Concurrency\n */\nfunction add(a, b) {\n  return a + b;\n}\n\nfunction print(n) {\n  console.log(`Two times the number ${n} is ` + add(n, n));\n}\n\nprint(5);\n```\n\nHere, 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.\n\nNow 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to kill child processes that spawn their own child processes in Node.js?\n\nIf a child process in Node.js spawn their own child processes, kill() method will not kill the child process\\'s own child processes. For example, if I start a process that starts it\\'s own child processes via child_process module, killing that child process will not make my program to quit.\n\n```js\nconst spawn = require('child_process').spawn;\nconst child = spawn('my-command');\n\nchild.kill();\n```\n\nThe program above will not quit if `my-command` spins up some more processes.\n\n**PID range hack:**\n\nWe can start child processes with {detached: true} option so those processes will not be attached to main process but they will go to a new group of processes. Then using process.kill(-pid) method on main process we can kill all processes that are in the same group of a child process with the same pid group. In my case, I only have one processes in this group.\n\n```js\nconst spawn = require('child_process').spawn;\nconst child = spawn('my-command', {detached: true});\n\nprocess.kill(-child.pid);\n```\n\nPlease note - before pid. This converts a pid to a group of pids for process kill() method.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is load balancer and how it works?\n\nA load balancer is a process that takes in HTTP requests and forwards these HTTP requests to one of a collection of servers. Load balancers are usually used for performance purposes: if a server needs to do a lot of work for each request, one server might not be enough, but 2 servers alternating handling incoming requests might.\n\n**1. Using cluster module:**\n\nNodeJS has a built-in module called Cluster Module to take the advantage of a multi-core system. Using this module you can launch NodeJS instances to each core of your system. Master process listening on a port to accept client requests and distribute across the worker using some intelligent fashion. So, using this module you can utilize the working ability of your system.\n\n**2. Using PM2:**\n\nPM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without the downtime and to facilitate common system admin tasks.\n\n```js\n$ pm2 start app.js -i max --name \"Balancer\"\n```\n\nThis command will run the app.js file on the cluster mode to the total no of core available on your server.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/pm2-load-balancer.png\" alt=\"Load Balancing using PM2\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\n**3. Using Express module:**\n\nThe below code basically creates two Express Servers to handle the request\n\n```js\nconst body = require('body-parser');\nconst express = require('express');\n\nconst app1 = express();\nconst app2 = express();\n\n// Parse the request body as JSON\napp1.use(body.json());\napp2.use(body.json());\n\nconst handler = serverNum =\u003e (req, res) =\u003e {\n  console.log(`server ${serverNum}`, req.method, req.url, req.body);\n  res.send(`Hello from server ${serverNum}!`);\n};\n\n// Only handle GET and POST requests\napp1.get('*', handler(1)).post('*', handler(1));\napp2.get('*', handler(2)).post('*', handler(2));\n\napp1.listen(3000);\napp2.listen(3001);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between `spawn()` and `fork()` methods in Node.js?\n\n**1. spawn():**\n\nIn Node.js, spawn() launches a new process with the available set of commands. This doesn\\'t generate a new V8 instance only a single copy of the node module is active on the processor. It is used when we want the child process to return a large amount of data back to the parent process.\n\nWhen spawn is called, it creates a **streaming interface** between the parent and child process. Streaming Interface — one-time buffering of data in a binary format.\n\n**Example:**\n\n```js\n/**\n * The spawn() method\n */\nconst { spawn } = require(\"child_process\");\nconst child = spawn(\"dir\", [\"D:\\\\empty\"], { shell: true });\n\nchild.stdout.on(\"data\", (data) =\u003e {\n  console.log(`stdout ${data}`);\n});\n```\n\nOutput\n\n```js\nstdout  Volume in drive D is Windows\n Volume Serial Number is 76EA-3749\n\nstdout\n Directory of D:\\\n```\n\n**2. fork():**\n\nThe **fork()** is a particular case of **spawn()** which generates a new V8 engines instance. Through this method, multiple workers run on a single node code base for multiple tasks. It is used to separate computation-intensive tasks from the main event loop.\n\nWhen fork is called, it creates a **communication channel** between the parent and child process Communication Channel — messaging\n\n**Example:**\n\n```js\n/**\n * The fork() method\n */\nconst { fork } = require(\"child_process\");\n\nconst forked = fork(\"child.js\");\n\nforked.on(\"message\", (msg) =\u003e {\n  console.log(\"Message from child\", msg);\n});\n\nforked.send({ message: \"fork() method\" });\n```\n\n```js\n/**\n * child.js\n */\nprocess.on(\"message\", (msg) =\u003e {\n  console.log(\"Message from parent:\", msg);\n});\n\nlet counter = 0;\n\nsetInterval(() =\u003e {\n  process.send({ counter: counter++ });\n}, 1000);\n```\n\nOutput:\n\n```js\nMessage from parent: { message: 'fork() method' }\nMessage from child { counter: 0 }\nMessage from child { counter: 1 }\nMessage from child { counter: 2 }\n...\n...\nMessage from child { counter: n }\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is daemon process?\n\nA daemon is a program that runs in background and has no controlling terminal. They are often used to provide background services. For example, a web-server or a database server can run as a daemon.\n\nWhen a daemon process is initialized:\n\n* It creates a child of itself and proceeds to shut down all standard descriptors (error, input, and output) from this particular copy.\n* It closes the parent process when the user closes the session/terminal window.\n* Leaves the child process running as a daemon.\n\n**Daemonize Node.js process:**\n\n* [Forever](https://github.com/foreversd/forever)\n* [PM2](https://github.com/Unitech/pm2)\n* [Nodemon](https://github.com/remy/nodemon/)\n* [Supervisor](https://github.com/Supervisor/supervisor)\n* [Docker](https://github.com/docker)\n\n**Example:** Using an instance of Forever from Node.js\n\n```js\nconst forever = require(\"forever\");\n\nconst child = new forever.Forever(\"your-filename.js\", {\n  max: 3,\n  silent: true,\n  args: [],\n});\n\nchild.on(\"exit\", this.callback);\nchild.start();\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 9. NODE.JS WEB MODULE\n\n\u003cbr/\u003e\n\n## Q. How to use JSON Web Token (JWT) for authentication in Node.js?\n\nJSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.\n\nThere are some advantages of using JWT for authorization:\n\n* Purely stateless. No additional server or infra required to store session information.\n* It can be easily shared among services.\n\n**Syntax:**\n\n```js\njwt.sign(payload, secretOrPrivateKey, [options, callback])\n```\n\n* **Header** - Consists of two parts: the type of token (i.e., JWT) and the signing algorithm (i.e., HS512)\n* **Payload** - Contains the claims that provide information about a user who has been authenticated along with other information such as token expiration time.\n* **Signature** - Final part of a token that wraps in the encoded header and payload, along with the algorithm and a secret\n\n**Installation:**\n\n```js\nnpm install jsonwebtoken bcryptjs --save\n```\n\n**Example**:\n\n```js\n/**\n * AuthController.js\n */\nconst express = require('express');\nconst router = express.Router();\nconst bodyParser = require('body-parser');\nconst User = require('../user/User');\n\nconst jwt = require('jsonwebtoken');\nconst bcrypt = require('bcryptjs');\nconst config = require('../config');\n\n\nrouter.use(bodyParser.urlencoded({ extended: false }));\nrouter.use(bodyParser.json());\n\nrouter.post('/register', function(req, res) {\n  \n  let hashedPassword = bcrypt.hashSync(req.body.password, 8);\n  \n  User.create({\n    name : req.body.name,\n    email : req.body.email,\n    password : hashedPassword\n  },\n  function (err, user) {\n    if (err) return res.status(500).send(\"There was a problem registering the user.\")\n    // create a token\n    let token = jwt.sign({ id: user._id }, config.secret, {\n      expiresIn: 86400 // expires in 24 hours\n    });\n    res.status(200).send({ auth: true, token: token });\n  });\n});\n```\n\n**config.js:**\n\n```js\n/**\n * config.js\n */\nmodule.exports = {\n  'secret': 'supersecret'\n};\n```\n\nThe `jwt.sign()` method takes a payload and the secret key defined in `config.js` as parameters. It creates a unique string of characters representing the payload. In our case, the payload is an object containing only the id of the user.\n\n**Reference:**\n\n* *[https://www.npmjs.com/package/jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to build a microservices architecture with Node.js?\n\nMicroservices are a style of **Service Oriented Architecture (SOA)** where the app is structured on an assembly of interconnected services. With microservices, the application architecture is built with lightweight protocols. The services are finely seeded in the architecture. Microservices disintegrate the app into smaller services and enable improved modularity.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/monolithic-and-microservices-architecture.jpg\" alt=\"Microservices\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\nThere are few things worth emphasizing about the superiority of microservices, and distributed systems generally, over monolithic architecture:\n\n* **Modularity** — responsibility for specific operations is assigned to separate pieces of the application\n* **Uniformity** — microservices interfaces (API endpoints) consist of a base URI identifying a data object and standard HTTP methods (GET, POST, PUT, PATCH and DELETE) used to manipulate the object\n* **Robustness** — component failures cause only the absence or reduction of a specific unit of functionality\n* **Maintainability** — system components can be modified and deployed independently\n* **Scalability** — instances of a service can be added or removed to respond to changes in demand.\n* **Availability** — new features can be added to the system while maintaining 100% availability.\n* **Testability** — new solutions can be tested directly in the production environment by implementing them for  restricted segments of users to see how they behave in real life.\n\n**Example:** Creating Microservices with Node.js\n\n**Step 01:** Creating a Server to Accept Requests\n\nThis file is creating our server and assigns routes to process all requests.\n\n```js\n//  server.js\n\nconst express = require('express')\nconst app = express();\nconst port = process.env.PORT || 3000;\n\nconst routes = require('./api/routes');\nroutes(app);\napp.listen(port, function() {\n   console.log('Server started on port: ' + port);\n});\n```\n\n**Step 02:** Defining the routes\n\nThe next step is to define the routes for the microservices and then assign each to a target in the controller. We have two endpoints. One endpoint called \"about\" that returns information about the application. And a \"distance\" endpoint that includes two path parameters, both Zip Codes of the Lego store. This endpoint returns the distance, in miles, between these two Zip Codes.\n\n```js\nconst controller = require('./controller');\n\nmodule.exports = function(app) {\n   app.route('/about')\n       .get(controller.about);\n   app.route('/distance/:zipcode1/:zipcode2')\n       .get(controller.getDistance);\n};\n```\n\n**Step 03:** Adding Controller Logic\n\nWithin the controller file, we are going to create a controller object with two properties. Those properties are the functions to handle the requests we defined in the routes module.\n\n```js\nconst properties = require('../package.json')\nconst distance = require('../service/distance');\n\nconst controllers = {\n   about: function(req, res) {\n       let aboutInfo = {\n           name: properties.name,\n           version: properties.version\n       }\n       res.json(aboutInfo);\n   },\n   getDistance: function(req, res) {\n           distance.find(req, res, function(err, dist) {\n               if (err)\n                   res.send(err);\n               res.json(dist);\n           });\n       },\n};\n\nmodule.exports = controllers;\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How microservices communicate with each other?\n\nMicroservices are an architectural style and comprises of small modules/elements which are independent of each other. At times they are interdependent on other microservices or even a database. Breaking down applications into smaller elements brings scalability and efficiency to the structure.\n\nThe microservices are distributed and communicate with each other by inter-service communication on network level. Each microservice has its own instance and process. Therefore, services must interact using an inter-service communication protocols like HTTP, gRPC or message brokers AMQP protocol.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/microservices-communication.png\" alt=\"Microservices Communication\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\nClient and services communicate with each other with many different types of communication. Mainly, those types of communications can be classified in two axes.\n\n**1. Synchronous Communication:**\n\nThe Synchronous communication is using HTTP or gRPC protocol for returning sync response. The client sends a request and waits for a response from the service. So that means client code block their thread, until the response reach from the server.\n\n**2. Asynchronous Communication:**\n\nIn Asynchronous communication, the client sends a request but it doesn\\'t wait for a response from the service. The most popular protocol for this Asynchronous communications is AMQP (Advanced Message Queuing Protocol). So with using AMQP protocols, the client sends the message with using message broker systems like Kafka and RabbitMQ queue. The message producer usually does not wait for a response. This message consume from the subscriber systems in async way, and no one waiting for response suddenly.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 10. NODE.JS MIDDLEWARE\n\n\u003cbr/\u003e\n\n## Q. What are the middleware functions in Node.js?\n\nMiddleware 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.\n\nMiddleware functions can perform the following tasks:\n\n* Execute any code.\n* Make changes to the request and the response objects.\n* End the request-response cycle.\n* Call the next middleware in the stack.\n\nIf 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.\n\nThe following figure shows the elements of a middleware function call:\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/express-mw.png\" alt=\"Middleware functions\" width=\"800px\" /\u003e\n\u003c/p\u003e\n\nMiddleware 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain the use of next in Node.js?\n\nThe **next** is a function in the Express router which executes the middleware succeeding the current middleware.\n\n**Example:**\n\nTo load the middleware function, call `app.use()`, specifying the middleware function. For example, the following code loads the **myLogger** middleware function before the route to the root path (/).\n\n```js\n/**\n * myLogger\n */\nconst express = require(\"express\");\nconst app = express();\n\nconst myLogger = function (req, res, next) {\n  console.log(\"LOGGED\");\n  next();\n};\n\napp.use(myLogger);\n\napp.get(\"/\", (req, res) =\u003e {\n  res.send(\"Hello World!\");\n});\n\napp.listen(3000);\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/next-function-nq042s)**\n\n*Note: The `next()` function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The `next()` function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why to use Express.js?\n\nExpress.js is a Node.js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application.\n\n**Features of Express.js:**\n\n* **Fast Server-Side Development:** The features of node js help express saving a lot of time.\n* **Middleware:** Middleware is a request handler that has access to the application\\'s request-response cycle.\n* **Routing:** It refers to how an application\\'s endpoint\\'s URLs respond to client requests.\n* **Templating:** It provides templating engines to build dynamic content on the web pages by creating HTML templates on the server.\n* **Debugging:** Express makes it easier as it identifies the exact part where bugs are.\n\nThe 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.\n\n**Example:**\n\n```js\n/**\n * Simple server using Express.js\n */\nconst express = require(\"express\");\nconst app = express();\n\napp.get(\"/\", function (req, res) {\n  res.send(\"Hello World!\");\n});\n\nconst server = app.listen(3000, function () {});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why should you separate Express 'app' and 'server'?\n\nKeeping the API declaration separated from the network related configuration (port, protocol, etc) allows testing the API in-process, without performing network calls, with all the benefits that it brings to the table: fast testing execution and getting coverage metrics of the code. It also allows deploying the same API under flexible and different network conditions.\n\nAPI declaration, should reside in app.js:\n\n```js\n/**\n * app.js\n */\nconst app = express();\n\napp.use(bodyParser.json());\napp.use(\"/api/events\", events.API);\napp.use(\"/api/forms\", forms);\n```\n\nServer network declaration\n\n```js\n/**\n * server.js\n */\nconst app = require('../app');\nconst http = require('http');\n\n\n// Get port from environment and store in Express.\nconst port = normalizePort(process.env.PORT || '3000');\napp.set('port', port);\n\n\n// Create HTTP server.\nconst server = http.createServer(app);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are some of the most popular packages of Node.js?\n\n| Package  | Description                                      |\n|----------|--------------------------------------------------|\n|async     | Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript|\n|axios     |Axios is a promise-based HTTP Client for node.js and the browser.|\n|autocannon|AutoCannon is a tool for performance testing and a tool for benchmarking.|\n|browserify|Browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single `\u003cscript\u003e` tag|\n|bower     |Bower is a package manager for the web It works by fetching and installing packages from all over, taking care of hunting, finding, downloading, and saving the stuff you\\'re looking for|\n|csv       |csv module has four sub modules which provides CSV generation, parsing, transformation and serialization for Node.js|\n|debug     |Debug is a tiny node.js debugging utility modelled after node core\\'s debugging technique|\n|express   |Express is a fast, un-opinionated, minimalist web framework. It provides small, robust tooling for HTTP servers, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs|\n|grunt     |is a JavaScript Task Runner that facilitates creating new projects and makes performing repetitive but necessary tasks such as linting, unit testing, concatenating and minifying files (among other things) trivial|\n|http-server|is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it\\'s simple and hackable enough to be used for testing, local development, and learning|\n|inquirer  |A collection of common interactive command line user interfaces|\n|jshint    |Static analysis tool to detect errors and potential problems in JavaScript code and to enforce your team\\'s coding conventions|\n|koa       |Koa is web app framework. It is an expressive HTTP middleware for node.js to make web applications and APIs more enjoyable to write|\n|lodash    |The lodash library exported as a node module. Lodash is a modern JavaScript utility library delivering modularity, performance, \u0026 extras|\n|less      |The less library exported as a node module|\n|moment    |A lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates|\n|mongoose  |It is a MongoDB object modeling tool designed to work in an asynchronous environment|\n|mongoDB   |The official MongoDB driver for Node.js. It provides a high-level API on top of mongodb-core that is meant for end users|\n|nodemon   |It is a simple monitor script for use during development of a node.js app, It will watch the files in the directory in which nodemon was started, and if any files change, nodemon will automatically restart your node application|\n|nodemailer|This module enables e-mail sending from a Node.js applications|\n|passport  |A simple, unobtrusive authentication middleware for Node.js. Passport uses the strategies to authenticate requests. Strategies can range from verifying username and password credentials or authentication using OAuth or OpenID|\n|socket.io |Its a node.js realtime framework server|\n|sails     |Sails is a API-driven framework for building realtime apps, using MVC conventions (based on Express and Socket.io)|\n|underscore|Underscore.js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects|\n|validator |A nodejs module for a library of string validators and sanitizers|\n|winston   |A multi-transport async logging library for Node.js|\n|ws        |A simple to use, blazing fast and thoroughly tested websocket client, server and console for node.js|\n|xml2js    |A Simple XML to JavaScript object converter|\n|yo        |A CLI tool for running Yeoman generators|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can you make sure your dependencies are safe?\n\nThe only option is to automate the update / security audit of your dependencies. For that there are free and paid options:\n\n1. npm outdated\n2. Trace by RisingStack\n3. NSP\n4. GreenKeeper\n5. Snyk\n6. npm audit\n7. npm audit fix\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the security mechanisms available in Node.js?\n\n**1. Helmet module:**\n\n[Helmet](https://www.npmjs.com/package/helmet) helps to secure your Express applications by setting various HTTP headers, like:\n\n* X-Frame-Options to mitigates clickjacking attacks,\n* Strict-Transport-Security to keep your users on HTTPS,\n* X-XSS-Protection to prevent reflected XSS attacks,\n* X-DNS-Prefetch-Control to disable browsers DNS prefetching.\n\n```js\n/**\n * Helmet\n */\nconst express = require('express')\nconst helmet = require('helmet')\nconst app = express()\n\napp.use(helmet())\n```\n\n**2. JOI module:**\n\nValidating user input is one of the most important things to do when it comes to the security of your application. Failing to do it correctly can open up your application and users to a wide range of attacks, including command injection, SQL injection or stored cross-site scripting.\n\nTo validate user input, one of the best libraries you can pick is joi. [Joi](https://www.npmjs.com/package/joi) is an object schema description language and validator for JavaScript objects.\n\n```js\n/**\n * Joi\n */\nconst Joi = require('joi');\n\nconst schema = Joi.object().keys({\n    username: Joi.string().alphanum().min(3).max(30).required(),\n    password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),\n    access_token: [Joi.string(), Joi.number()],\n    birthyear: Joi.number().integer().min(1900).max(2013),\n    email: Joi.string().email()\n}).with('username', 'birthyear').without('password', 'access_token')\n\n// Return result\nconst result = Joi.validate({\n    username: 'abc',\n    birthyear: 1994\n}, schema)\n// result.error === null -\u003e valid\n```\n\n**3. Regular Expressions:**\n\nRegular Expressions are a great way to manipulate texts and get the parts that you need from them. However, there is an attack vector called Regular Expression Denial of Service attack, which exposes the fact that most Regular Expression implementations may reach extreme situations for specially crafted input, that cause them to work extremely slowly.\n\nThe Regular Expressions that can do such a thing are commonly referred as Evil Regexes. These expressions contain:\n*grouping with repetition,\n*inside the repeated group:\n    *repetition, or\n    *alternation with overlapping  \n\nExamples of Evil Regular Expressions patterns:\n\n```js\n(a+)+\n([a-zA-Z]+)*\n(a|aa)+\n```\n\n**4. Security.txt:**\n\nSecurity.txt defines a standard to help organizations define the process for security researchers to securely disclose security vulnerabilities.\n\n```js\nconst express = require('express')\nconst securityTxt = require('express-security.txt')\n\nconst app = express()\n\napp.get('/security.txt', securityTxt({\n  // your security address\n  contact: 'email@example.com',\n  // your pgp key\n  encryption: 'encryption',\n  // if you have a hall of fame for securty resourcers, include the link here\n  acknowledgements: 'http://acknowledgements.example.com'\n}))\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is npm in Node.js?\n\nNPM stands for Node Package Manager. It provides following two main functionalities.\n\n* It works as an Online repository for node.js packages/modules which are present at \u003cnodejs.org\u003e.\n* It works as Command line utility to install packages, do version management and dependency management of Node.js packages.\nNPM comes bundled along with Node.js installable. We can verify its version using the following command-\n\n```js\nnpm --version\n```\n\nNPM helps to install any Node.js module using the following command.\n\n```js\nnpm install \u003cModule Name\u003e\n```\n\nFor example, following is the command to install a famous Node.js web framework module called express-\n\n```js\nnpm install express\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why npm shrinkwrap is useful?\n\nNPM shrinkwrap lets you lock down the ver­sions of installed pack­ages and their descen­dant pack­ages. It helps you use same package versions on all environments (development, staging, production) and also improve download and installation speed.\n\nAfter installing packages using npm install or npm install `\u003cpackage-name\u003e` and updating your **node_modules** folder, you should run\n\n```js\nnpm shrinkwrap\n```\n\nIt should create new **npm-shrinkwrap.json** file with information about all packages you use. Next time, when someone calls **npm install**, it will install packages from **npm-shrinkwrap.json** and you will have the same environment on all machines.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to handle file upload in Node.js?\n\nFile can be uploaded to the server using Multer module. Multer is a Node.js middleware which is used for handling multipart/form-data, which is mostly used library for uploading files.\n\n**1. Installing the dependencies:**\n\n```js\nnpm install express body-parser multer --save\n```\n\n**2. server.js:**\n\n```js\n/**\n * File Upload in Node.js\n */\nconst express = require(\"express\");\nconst bodyParser = require(\"body-parser\");\nconst multer = require(\"multer\");\nconst app = express();\n\n// for text/number data transfer between clientg and server\napp.use(bodyParser());\n\nconst storage = multer.diskStorage({\n  destination: function (req, file, callback) {\n    callback(null, \"./uploads\");\n  },\n  filename: function (req, file, callback) {\n    callback(null, file.fieldname + \"-\" + Date.now());\n  },\n});\n\nconst upload = multer({ storage: storage }).single(\"userPhoto\");\n\napp.get(\"/\", function (req, res) {\n  res.sendFile(__dirname + \"/index.html\");\n});\n\n// POST: upload for single file upload\napp.post(\"/api/photo\", function (req, res) {\n  upload(req, res, function (err) {\n    if (err) {\n      return res.end(\"Error uploading file.\");\n    }\n    res.end(\"File is uploaded\");\n  });\n});\n\napp.listen(3000, function () {\n  console.log(\"Listening on port 3000\");\n});\n```\n\n**3. index.html:**\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003ctitle\u003eMulter-File-Upload\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003ch1\u003eMULTER File Upload | Single File Upload\u003c/h1\u003e \n\n    \u003cform id = \"uploadForm\"\n         enctype = \"multipart/form-data\"\n         action = \"/api/photo\"\n         method = \"post\"\n    \u003e\n      \u003cinput type=\"file\" name=\"userPhoto\" /\u003e\n      \u003cinput type=\"submit\" value=\"Upload Image\" name=\"submit\"\u003e\n    \u003c/form\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain the terms body-parser, cookie-parser, morgan, nodemon, pm2, serve-favicon, cors, dotenv, fs-extra, moment in Express.js?\n\n**1. body-parser:**\n\n`body-parser` extract the entire body portion of an incoming request stream and exposes it on `req.body`. The body-parser module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST request.\n\n**Example:**\n\n```js\nnpm install body-parser\n```\n\n```js\n/**\n * body-parser\n */\nconst express = require(\"express\");\nconst bodyParser = require(\"body-parser\");\n\nconst app = express();\n\n// create application/json parser\nconst jsonParser = bodyParser.json();\n\n// create application/x-www-form-urlencoded parser\nconst urlencodedParser = bodyParser.urlencoded({ extended: false });\n\n// POST /login gets urlencoded bodies\napp.post(\"/login\", urlencodedParser, function (req, res) {\n  res.send(\"welcome, \" + req.body.username);\n});\n\n// POST /api/users gets JSON bodies\napp.post(\"/api/users\", jsonParser, function (req, res) {\n  // create user in req.body\n});\n```\n\n**2. cookie-parser:**\n\nA 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.\n\nThe `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.\n\n**Installation:**\n\n```js\nnpm install cookie-parser\n```\n\n**Example:**\n\n```js\n/**\n * cookie-parser\n */\nconst express = require('express')\nconst cookieParser = require('cookie-parser')\n\nconst app = express()\napp.use(cookieParser())\n\napp.get('/', function (req, res) {\n  // Cookies that have not been signed\n  console.log('Cookies: ', req.cookies)\n\n  // Cookies that have been signed\n  console.log('Signed Cookies: ', req.signedCookies)\n})\n\napp.listen(3000)\n```\n\n**3. morgan:**\n\nHTTP request logger middleware for node.js.\n\n**Installation:**\n\n```js\nnpm install morgan\n```\n\n**Example:**\n\n```js\n/**\n * Writing logs to a file\n */\nconst express = require('express')\nconst fs = require('fs')\nconst morgan = require('morgan')\nconst path = require('path')\n\nconst app = express()\n\n// create a write stream (in append mode)\nconst accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })\n\n// setup the logger\napp.use(morgan('combined', { stream: accessLogStream }))\n\napp.get('/', function (req, res) {\n  res.send('hello, world!')\n})\n```\n\n**4. nodemon:**\n\nNodemon is a utility that will monitor for any changes in source and automatically restart your server.\n\n**Installation:**\n\n```js\nnpm install -g nodemon\n```\n\n**Example:**\n\n```js\n{\n  // ...\n  \"scripts\": {\n    \"start\": \"nodemon server.js\"\n  },\n  // ...\n}\n```\n\n**5. pm2:**\n\n**P**(rocess) **M**(anager) **2** (pm2) is a production process manager for Node.js applications with a built-in load balancer. It allows to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.\n\n**Installation:**\n\n```js\nnpm install pm2 -g\n```\n\n**Start an application:**\n\n```js\npm2 start app.js\n```\n\n**Reference:**\n\n* *[https://pm2.keymetrics.io/docs/usage/quick-start/](https://pm2.keymetrics.io/docs/usage/quick-start/)*\n\n**6. serve-favicon:**\n\nNode.js middleware for serving a favicon. It create new middleware to serve a favicon from the given path to a favicon file. **path** may also be a Buffer of the icon to serve.\n\n**Installation:**\n\n```js\nnpm install serve-favicon\n```\n\n**Example:**\n\n```js\n/**\n * serve-favicon\n */\nconst express = require('express')\nconst favicon = require('serve-favicon')\nconst path = require('path')\n\nconst app = express()\napp.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))\n\n// Add your routes here, etc.\n\napp.listen(3000)\n```\n\n**7. cors:**\n\n**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.\n\n**Installation:**\n\n```js\nnpm install cors\n```\n\n**Example:**\n\n```js\n/**\n * Enable CORS for a Single Route\n */\nconst express = require('express')\nconst cors = require('cors')\nconst app = express()\n\napp.get('/products/:id', cors(), function (req, res, next) {\n  res.json({msg: 'This is CORS-enabled for a Single Route'})\n})\n\napp.listen(8080, function () {\n  console.log('CORS-enabled web server listening on port 80')\n})\n```\n\n**8. dotenv:**\n\nWhen 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`.\n\n**Installation:**\n\n```js\nnpm install dotenv\n```\n\n**Usage:**\n\n```js\n// .env\n\nDB_HOST=localhost\nDB_USER=admin\nDB_PASS=root\n```\n\n```js\n/**\n * config.js\n */\nconst db = require('db')\n\ndb.connect({\n  host: process.env.DB_HOST,\n  username: process.env.DB_USER,\n  password: process.env.DB_PASS\n})\n```\n\n**9. fs-extra:**\n\n`fs-extra` contains methods that aren\\'t included in the vanilla Node.js fs package. Such as recursive `mkdir`, `copy`, and `remove`. It also uses graceful-fs to prevent `EMFILE` errors.\n\n**Installation:**\n\n```js\nnpm install fs-extra\n```\n\n**Usage:**\n\n```js\n/**\n * fs-extra\n */\nconst fs = require('fs-extra')\n\n// Async with callbacks:\nfs.copy('/tmp/myfile', '/tmp/mynewfile', err =\u003e {\n  if (err) return console.error(err)\n  console.log('success!')\n})\n```\n\n**10. moment:**\n\nA JavaScript date library for parsing, validating, manipulating, and formatting dates.\n\n**Installation:**\n\n```js\nnpm install moment --save\n```\n\n**Usage:**\n\n* Format Dates\n\n```js\nconst moment = require('moment');\n\nmoment().format('MMMM Do YYYY, h:mm:ss a'); // October 24th 2022, 3:15:22 pm\nmoment().format('dddd');                    // Saturday\nmoment().format(\"MMM Do YY\");               // Oct 24th 22\n```\n\n* Relative Time\n\n```js\nconst moment = require('moment');\n\nmoment(\"20111031\", \"YYYYMMDD\").fromNow(); // 9 years ago\nmoment(\"20120620\", \"YYYYMMDD\").fromNow(); // 8 years ago\nmoment().startOf('day').fromNow();        // 15 hours ago\n```\n\n* Calendar Time\n\n```js\nconst moment = require('moment');\n\nmoment().subtract(10, 'days').calendar(); // 10/14/2022\nmoment().subtract(6, 'days').calendar();  // Last Sunday at 3:18 PM\nmoment().subtract(3, 'days').calendar();  // Last Wednesday at 3:18 PM\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 11. NODE.JS RESTFUL API\n\n\u003cbr/\u003e\n\n## Q. Explain RESTful Web Services in Node.js?\n\nREST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol.\nIt is an architectural style as well as an approach for communications purposes that is often used in various web services development. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol.\n\n**HTTP methods:**\n\n* `GET` − Provides read-only access to a resource.\n* `PUT` − Updates an existing resource or creates a new resource.\n* `DELETE` − Removes a resource.\n* `POST` − Creates a new resource.\n* `PATCH`− Update/modify a resource\n\n**Example:** users.json\n\n```json\n{\n   \"user1\" : {\n      \"id\": 1,\n      \"name\" : \"Ehsan Philip\",\n      \"age\" : 24\n   },\n\n   \"user2\" : {\n      \"id\": 2,\n      \"name\" : \"Karim Jimenez\",\n      \"age\" : 22\n   },\n\n   \"user3\" : {\n      \"id\": 3,\n      \"name\" : \"Giacomo Weir\",\n      \"age\" : 18\n   }\n}\n```\n\n**List Users** ( `GET` method)\n\nLet\\'s implement our first RESTful API listUsers using the following code in a server.js file −\n\n```js\nconst express = require('express');\nconst app = express();\nconst fs = require(\"fs\");\n\napp.get('/listUsers', function (req, res) {\n   fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n      console.log( data );\n      res.end( data );\n   });\n})\n\nconst server = app.listen(3000, function () {\n   const host = server.address().address\n   const port = server.address().port\n   console.log(\"App listening at http://%s:%s\", host, port)\n});\n```\n\n**Add User** ( `POST` method )\n\nFollowing API will show you how to add new user in the list. \n\n```js\nconst express = require('express');\nconst app = express();\nconst fs = require(\"fs\");\n\nconst user = {\n   \"user4\" : {\n      \"id\": 4,\n      \"name\" : \"Spencer Amos\",\n      \"age\" : 28\n   }\n}\n\napp.post('/addUser', function (req, res) {\n   // First read existing users.\n   fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n      data = JSON.parse( data );\n      data[\"user4\"] = user[\"user4\"];\n      console.log( data );\n      res.end( JSON.stringify(data));\n   });\n})\n\nconst server = app.listen(3000, function () {\n   const host = server.address().address\n   const port = server.address().port\n   console.log(\"App listening at http://%s:%s\", host, port)\n})\n```\n\n**Delete User:**\n\n```js\nconst express = require('express');\nconst app = express();\nconst fs = require(\"fs\");\n\nconst id = 2;\n\napp.delete('/deleteUser', function (req, res) {\n   // First read existing users.\n   fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n      data = JSON.parse( data );\n      delete data[\"user\" + 2];\n      console.log( data );\n      res.end( JSON.stringify(data));\n   });\n})\n\nconst server = app.listen(3000, function () {\n   const host = server.address().address\n   const port = server.address().port\n   console.log(\"App listening at http://%s:%s\", host, port)\n})\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between req.params and req.query?\n\nThe **req.params** are a part of a path in URL and they\\'re also known as URL variables. for example, if you have the route **/books/:id**, then the **id** property will be available as **req.params.id**. req.params default value is an empty object {}.\n\nA **req.query** is a part of a URL that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML form. A query is the last part of URL\n\n**Example 01:** req.params\n\n```js\n/**\n * req.params\n */\n\n// GET  http://localhost:3000/employees/10\n\napp.get('/employees/:id', (req, res, next) =\u003e {\n   console.log(req.params.id); // 10\n})\n```\n\n**Example 02:** req.query\n\n```js\n/**\n * req.query\n */\n\n// GET  http://localhost:3000/employees?page=20\n\napp.get('/employees', (req, res, next) =\u003e {\n  console.log(req.query.page) // 20\n})\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to make post request in Node.js?\n\nFollowing code snippet can be used to make a Post Request in Node.js.\n\n```js\n/**\n * POST Request\n */\nconst request = require(\"request\");\n\nrequest.post(\"http://localhost:3000/action\",  { form: { key: \"value\" } },\n  function (error, response, body) {\n    if (!error \u0026\u0026 response.statusCode === 200) {\n      console.log(body);\n    }\n  }\n);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are Promises in Node.js?\n\nIt 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.\n\nPromises 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).\n\nThe core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:\n\n* pending - The initial state of a promise.\n* fulfilled - The state of a promise representing a successful operation.\n* rejected - The state of a promise representing a failed operation.\nOnce a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).  \n\n**Example:**\n\n```js\n/**\n * Promise\n */\nfunction getSum(num1, num2) {\n  const myPromise = new Promise((resolve, reject) =\u003e {\n    if (!isNaN(num1) \u0026\u0026 !isNaN(num2)) {\n      resolve(num1 + num2);\n    } else {\n      reject(new Error(\"Not a valid number\"));\n    }\n  });\n\n  return myPromise;\n}\n\nconsole.log(getSum(10, 20)); // Promise { 30 }\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can you secure your HTTP cookies against XSS attacks?\n\n**1.** When the web server sets cookies, it can provide some additional attributes to make sure the cookies won\\'t be accessible by using malicious JavaScript. One such attribute is HttpOnly.\n\n```js\nSet-Cookie: [name]=[value]; HttpOnly\n```\n\nHttpOnly makes sure the cookies will be submitted only to the domain they originated from.\n\n**2.** The \"Secure\" attribute can make sure the cookies are sent over secured channel only.\n\n```js\nSet-Cookie: [name]=[value]; Secure\n```\n\n**3.** The web server can use X-XSS-Protection response header to make sure pages do not load when they detect reflected cross-site scripting (XSS) attacks.\n\n```js\nX-XSS-Protection: 1; mode=block\n```\n\n**4.** The web server can use HTTP Content-Security-Policy response header to control what resources a user agent is allowed to load for a certain page. It can help to prevent various types of attacks like Cross Site Scripting (XSS) and data injection attacks.\n\n```js\nContent-Security-Policy: default-src 'self' *.http://sometrustedwebsite.com\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to make an HTTP POST request using axios in Node.js?\n\n```js\n/**\n * POST Request using Axios\n */\nconst express = require(\"express\");\nconst app = express();\nconst axios = require(\"axios\");\n\napp.post(\"/user\", async (req, res) =\u003e {\n  try {\n    const payload = { name: \"Aashita Iyer\", email: \"aashita.iyer@email.com\" };\n    const response = await axios.post(\"http://httpbin.org/post\", payload);\n    console.log(response.data);\n    res.status(200).json(response.data);\n  } catch (err) {\n    res.status(500).json({ message: err });\n  }\n});\n\napp.listen(3000, function () {\n  console.log(`App listening at http://localhost:3000/`);\n});\n```\n\n**Output:**\n\n```js\n{\n  args: {},\n  data: '{\"name\":\"Aashita Iyer\",\"email\":\"aashita.iyer@email.com\"}',\n  files: {},\n  form: {},\n  headers: {\n    Accept: 'application/json, text/plain, */*',\n    'Accept-Encoding': 'gzip, deflate, br',\n    'Content-Length': '56',\n    'Content-Type': 'application/json',\n    Host: 'httpbin.org',\n    'User-Agent': 'axios/1.1.3',\n    'X-Amzn-Trace-Id': 'Root=1-635cd3d3-1f13ea981467e6371ce3a740'\n  },\n  json: { email: 'aashita.iyer@email.com', name: 'Aashita Iyer' },\n  origin: 'xx.xx.xx.xx',\n  url: 'http://httpbin.org/post'\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is asynchronous programming in Node.js?\n\nAsynchronous 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between Asynchronous and Non-blocking?\n\n**1. Asynchronous:**\n\nThe 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.\n\n**2. Non-Blocking:**\n\nNonblocking 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How node.js prevents blocking code?\n\n**Blocking vs Non-blocking:**\n\n**Blocking** is when the execution of additional JavaScript in the Node.js process must wait until a non-JavaScript operation completes. This happens because the event loop is unable to continue running JavaScript while a **blocking** operation is occurring.\n\nSynchronous methods in the Node.js standard library that use **libuv** are the most commonly used blocking operations. Native modules may also have blocking methods. Blocking methods execute `synchronously` and non-blocking methods execute `asynchronously`.\n\n**Example:**\n\n```js\n// Blocking\nconst fs = require('fs');\nconst data = fs.readFileSync('/file.md'); // blocks here until file is read\nconsole.log(data);\nmoreWork(); // will run after console.log\n\n// Non-blocking\nconst fs = require('fs');\nfs.readFile('/file.md', (err, data) =\u003e {\n  if (err) throw err;\n  console.log(data);\n});\nmoreWork(); // will run before console.log\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Name the types of API functions in Node.js?\n\nThere are two types of API functions in Node.js:\n\n* Asynchronous, Non-blocking functions\n* Synchronous, Blocking functions\n\n**1. Blocking functions:**\n\nIn a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously.\n\n**Example:**\n\n```js\nconst fs = require('fs');\nconst data = fs.readFileSync('/file.md'); // blocks here until file is read\nconsole.log(data);\n// moreWork(); will run after console.log\n```\n\nThe second line of code blocks the execution of additional JavaScript until the entire file is read. moreWork () will only be called after Console.log\n\n**2. Non-blocking functions:**\n\nIn a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted. Non-blocking functions execute asynchronously.\n\n**Example:**\n\n```js\nconst fs = require('fs');\nfs.readFile('/file.md', (err, data) =\u003e {\n  if (err) throw err;\n  console.log(data);\n});\n// moreWork(); will run before console.log\n```\n\nSince `fs.readFile()` is non-blocking, moreWork() does not have to wait for the file read to complete before being called. This allows for higher throughput.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between put and patch?\n\nPUT and PATCH are HTTP verbs and they both relate to updating a resource. The main difference between PUT and PATCH requests are in the way the server processes the enclosed entity to modify the resource identified by the Request-URI.\n\nIn a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced.\n\nWith PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.\n\nAlso, another difference is that when you want to update a resource with PUT request, you have to send the full payload as the request whereas with PATCH, you only send the parameters which you want to update.\n\nThe most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them.\n\n* `POST` - create\n* `GET`  - read  \n* `PUT`  - update\n* `DELETE` - delete\n\n**PATCH**: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. List types of Http requests supported by Node.js?\n\nThe HTTP core module is a key module to Node.js networking.\n\n```js\nconst http = require('http')\n```\n\n**http.METHODS**\n\n```js\nrequire('http').METHODS\n[ 'ACL',\n  'BIND',\n  'CHECKOUT',\n  'CONNECT',\n  'COPY',\n  'DELETE',\n  'GET',\n  'HEAD',\n  'LINK',\n  'LOCK',\n  'M-SEARCH',\n  'MERGE',\n  'MKACTIVITY',\n  'MKCALENDAR',\n  'MKCOL',\n  'MOVE',\n  'NOTIFY',\n  'OPTIONS',\n  'PATCH',\n  'POST',\n  'PROPFIND',\n  'PROPPATCH',\n  'PURGE',\n  'PUT',\n  'REBIND',\n  'REPORT',\n  'SEARCH',\n  'SUBSCRIBE',\n  'TRACE',\n  'UNBIND',\n  'UNLINK',\n  'UNLOCK',\n  'UNSUBSCRIBE' ]\n  ```\n\n**http.STATUS_CODES**\n\n  ```js\n  require('http').STATUS_CODES\n{ '100': 'Continue',\n  '101': 'Switching Protocols',\n  '102': 'Processing',\n  '200': 'OK',\n  '201': 'Created',\n  '202': 'Accepted',\n  '203': 'Non-Authoritative Information',\n  '204': 'No Content',\n  '205': 'Reset Content',\n  '206': 'Partial Content',\n  '207': 'Multi-Status',\n  '208': 'Already Reported',\n  '226': 'IM Used',\n  '300': 'Multiple Choices',\n  '301': 'Moved Permanently',\n  '302': 'Found',\n  '303': 'See Other',\n  '304': 'Not Modified',\n  '305': 'Use Proxy',\n  '307': 'Temporary Redirect',\n  '308': 'Permanent Redirect',\n  '400': 'Bad Request',\n  '401': 'Unauthorized',\n  '402': 'Payment Required',\n  '403': 'Forbidden',\n  '404': 'Not Found',\n  '405': 'Method Not Allowed',\n  '406': 'Not Acceptable',\n  '407': 'Proxy Authentication Required',\n  '408': 'Request Timeout',\n  '409': 'Conflict',\n  '410': 'Gone',\n  '411': 'Length Required',\n  '412': 'Precondition Failed',\n  '413': 'Payload Too Large',\n  '414': 'URI Too Long',\n  '415': 'Unsupported Media Type',\n  '416': 'Range Not Satisfiable',\n  '417': 'Expectation Failed',\n  '418': 'I\\'m a teapot',\n  '421': 'Misdirected Request',\n  '422': 'Unprocessable Entity',\n  '423': 'Locked',\n  '424': 'Failed Dependency',\n  '425': 'Unordered Collection',\n  '426': 'Upgrade Required',\n  '428': 'Precondition Required',\n  '429': 'Too Many Requests',\n  '431': 'Request Header Fields Too Large',\n  '451': 'Unavailable For Legal Reasons',\n  '500': 'Internal Server Error',\n  '501': 'Not Implemented',\n  '502': 'Bad Gateway',\n  '503': 'Service Unavailable',\n  '504': 'Gateway Timeout',\n  '505': 'HTTP Version Not Supported',\n  '506': 'Variant Also Negotiates',\n  '507': 'Insufficient Storage',\n  '508': 'Loop Detected',\n  '509': 'Bandwidth Limit Exceeded',\n  '510': 'Not Extended',\n  '511': 'Network Authentication Required' }\n  ```\n\n**Making HTTP Requests**\n\n```js\nconst request = require('request');\n\nrequest('https://nodejs.org/', function(err, res, body) {\n    console.log(body);\n});\n```\n\nThe first argument to request can either be a URL string, or an object of options. Here are some of the more common options you\\'ll encounter in your applications:\n\n* **url**: The destination URL of the HTTP request\n* **method**: The HTTP method to be used (GET, POST, DELETE, etc)\n* **headers**: An object of HTTP headers (key-value) to be set in the request\n* **form**: An object containing key-value form data\n\n```js\nconst request = require('request');\n\nconst options = {\n    url: 'https://nodejs.org/file.json',\n    method: 'GET',\n    headers: {\n        'Accept': 'application/json',\n        'Accept-Charset': 'utf-8',\n        'User-Agent': 'my-reddit-client'\n    }\n};\n\nrequest(options, function(err, res, body) {\n    let json = JSON.parse(body);\n    console.log(json);\n});\n```\n\nUsing the options object, this request uses the GET method to retrieve JSON data directly from Reddit, which is returned as a string in the body field. From here, you can use `JSON.parse` and use the data as a normal JavaScript object.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between promises and async-await in Node.js?\n\n**1. Promises:**\n\nA promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed. This way, other operations can keep running without interruption.\n\n**States of Promises:**\n\n* `Pending`: Initial State, before the Promise succeeds or fails.\n* `Resolved`: Completed Promise\n* `Rejected`: Failed Promise, throw an error\n\n**Example:**\n\n```js\nfunction logFetch(url) {\n  return fetch(url)\n    .then(response =\u003e {\n      console.log(response);\n    })\n    .catch(err =\u003e {\n      console.error('fetch failed', err);\n    });\n}\n```\n\n**2. Async-Await:**\n\n`Await` is basically syntactic sugar for **Promises**. It makes asynchronous code look more like synchronous/procedural code, which is easier for humans to understand.\n\nPutting the keyword `async` before a function tells the function to return a Promise. If the code returns something that is not a `Promise`, then JavaScript automatically wraps it into a resolved promise with that value. The `await` keyword simply makes JavaScript wait until that `Promise` settles and then returns its result.\n\n**Example:**\n\n```js\nasync function logFetch(url) {\n  try {\n    const response = await fetch(url);\n    console.log(response);\n  }\n  catch (err) {\n    console.log('fetch failed', err);\n  }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Mention the steps by which you can async in Node.js?\n\nES 2017 introduced Asynchronous functions. Async functions are essentially a cleaner way to work with asynchronous code in JavaScript. \n\n**1. Async/Await:**\n\n* The newest way to write asynchronous code in JavaScript.\n* It is non blocking (just like promises and callbacks).\n* Async/Await was created to simplify the process of working with and writing chained promises.\n* Async functions return a Promise. If the function throws an error, the Promise will be rejected. If the function returns a value, the Promise will be resolved.  \n\nSyntax\n\n```js\n// Normal Function\nfunction add(x,y){\n  return x + y;\n}\n// Async Function\nasync function add(x,y){\n  return x + y;\n}\n```\n\n**2. Await:**\n\nAsync functions can make use of the await expression. This will pause the async function and wait for the Promise to resolve prior to moving on.  \n\n**Example:**\n\n```js\nfunction doubleAfter2Seconds(x) {\n  return new Promise(resolve =\u003e {\n    setTimeout(() =\u003e {\n      resolve(x * 2);\n    }, 2000);\n  });\n}\n\nasync function addAsync(x) {\n  const a = await doubleAfter2Seconds(10);\n  const b = await doubleAfter2Seconds(20);\n  const c = await doubleAfter2Seconds(30);\n  return x + a + b + c;\n}\n\n\naddAsync(10).then((sum) =\u003e {\n  console.log(sum);\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use promise in Node.js?\n\nA promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.\n\nPromise is relatively an easy implementation for asynchronous operation. The promise object returned from the function represents an operation which is not completed yet, but it guarantees to the caller of the operation that the operation will be completed in future.\n\nPromise has the following states:\n\n* **Pending** - asynchronous operation is not yet completed.\n* **Fulfilled** - asynchronous operation is completed successfully.\n* **Rejected** - asynchronous operation is terminated with an error.\n* **Settled** - asynchronous operation is either fulfilled or rejected.\n* **Callback** - function is executed if the promise is executed with value.\n* **Errback** - function is executed if the promise is rejected.\n\n**Moving to Promises from Callback:**\n\nOn the first pass, promises can mitigate the **Pyramid of Doom**: the situation where code marches to the right faster than it marches forward.\n\n```js\nstep1(function (value1) {\n    step2(value1, function(value2) {\n        step3(value2, function(value3) {\n            step4(value3, function(value4) {\n                // Do something with value4\n            });\n        });\n    });\n});\n```\n\nWith a promise library, it can flatten the pyramid.\n\n```js\nconst myPromise = new Promise((resolve, reject) =\u003e {\n  setTimeout(() =\u003e {\n    resolve(\"successful\");\n  }, 100);\n});\n\nmyPromise\n  .then(handleFulfilledA)\n  .then(handleFulfilledB)\n  .then(handleFulfilledC)\n  .catch(handleRejectedAny);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to perform get request using axios in nodejs?\n\n```js\n/**\n * Get Request using Axios\n */\nconst express = require(\"express\");\nconst app = express();\nconst axios = require(\"axios\");\n\napp.get(\"/async\", async (req, res) =\u003e {\n  try {\n    const response = await axios.get(\"https://jsonplaceholder.typicode.com/todos/1\");\n    res.status(200).json(response.data);\n  } catch (err) {\n    res.status(500).json({ message: err });\n  }\n});\n\napp.listen(3000, function () {\n  console.log(`App listening at http://localhost:3000/`);\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 12. NODE.JS ROUTING\n\n\u003cbr/\u003e\n\n## Q. How does routing work in Node.js?\n\nRouting defines the way in which the client requests are handled by the application endpoints. We define routing using methods of the Express app object that correspond to HTTP methods; for example, `app.get()` to handle `GET` requests and `app.post` to handle `POST` requests, `app.all()` to handle all HTTP methods and `app.use()` to specify middleware as the callback function.\n\nThese routing methods \"listens\" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.\n\n*Syntax*:\n\n```js\napp.METHOD(PATH, HANDLER)\n```\n\nWhere:\n\n* app is an instance of express.\n* METHOD is an `HTTP request method`.\n* PATH is a path on the server.\n* HANDLER is the function executed when the route is matched.\n\n**a) Route methods:**\n\n```js\n// GET method route\napp.get('/', function (req, res) {\n  res.send('GET request')\n})\n\n// POST method route\napp.post('/login', function (req, res) {\n  res.send('POST request')\n})\n\n// ALL method route\napp.all('/secret', function (req, res, next) {\n  console.log('Accessing the secret section ...')\n  next() // pass control to the next handler\n})\n```\n\n**b) Route paths:**\n\nRoute paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.\n\nThe characters `?`, `+`, `*`, and `()` are subsets of their regular expression counterparts. The hyphen `(-)` and the dot `(.)` are interpreted literally by string-based paths.\n\n**Example:**\n\n```js\n// This route path will match requests to /about.\napp.get('/about', function (req, res) {\n  res.send('about')\n})\n\n\n// This route path will match acd and abcd.\napp.get('/ab?cd', function (req, res) {\n  res.send('ab?cd')\n})\n\n\n// This route path will match butterfly and dragonfly\napp.get(/.*fly$/, function (req, res) {\n  res.send('/.*fly$/')\n})\n```\n\n**c) Route parameters:**\n\nRoute parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the `req.params` object, with the name of the route parameter specified in the path as their respective keys.\n\n**Example:**\n\n```js\napp.get('/users/:userId', function (req, res) {\n  res.send(req.params)\n})\n```\n\n**Response methods:**\n\n| Method            | Description                   |\n|-------------------|-------------------------------|\n|`res.download()`   |Prompt a file to be downloaded.|\n|`res.end()`        |End the response process.|\n|`res.json()`       |Send a JSON response.|\n|`res.jsonp()`      |Send a JSON response with JSONP support.|\n|`res.redirect()`   |Redirect a request.|\n|`res.render()`     |Render a view template.|\n|`res.send()`       |Send a response of various types.|\n|`res.sendFile()`   |Send a file as an octet stream.|\n|`res.sendStatus()` |Set the response status code and send its string representation as the response body.|\n\n**d) Router method:**\n\n```js\nconst express = require('express')\nconst router = express.Router()\n\n// middleware that is specific to this router\nrouter.use(function timeLog (req, res, next) {\n  console.log('Time: ', Date.now())\n  next()\n})\n\n// define the home page route\nrouter.get('/', function (req, res) {\n  res.send('Birds home page')\n})\n\n// define the about route\nrouter.get('/about', function (req, res) {\n  res.send('About birds')\n})\n\nmodule.exports = router\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 13. NODE.JS CACHING\n\n\u003cbr/\u003e\n\n## Q. How to access cache data in Node.js?\n\nCaching is a technique used in web development to handle performance bottlenecks related to how data is managed, stored, and retrieved. A cache layer or server acts as a secondary storage layer, usually faster and highly performant to temporarily store a subset of data. It is expected that data stored in a cache does not change often. Cache can be stored using various techniques like in-memory cache, file cache or a separate cache database.\n\n**Installation:**\n\n```js\nnpm install express node-cache axios\n```\n\n**Node-cache has following major functions:**\n\n* **.set(key, val, [ ttl ]):** Used to set some value corresponding to a particular key in the cache. This same key must be used to retrieve this value.\n* **.get(key):** Used to get value set to specified key. It returns undefined, if the key is not already present.\n* **has(key):** Used to check if the cache already has some value set for specified key. Returns true if present otherwise false.\n\n**Implement in-memory cache with following approach:**\n\n* On API request, check if the cache has key already set using has(key) function\n* If the cache has the key, retrieve the cached value by get(key) function and use it instead of performing operation again. (This saves time)\n* If the cache doesn\\'t have a key, perform the operations required, and before sending the response, set the value for that key so that further requests can be responded to directly through cached data.\n\n**Example:**\n\n```js\n/**\n * In-Memory Cache \n */\nconst express = require(\"express\");\nconst NodeCache = require(\"node-cache\");\nconst axios = require(\"axios\");\n\nconst app = express();\nconst cache = new NodeCache({ stdTTL: 15 });\n\n/**\n * GET Cached Data\n */\nconst verifyCache = (req, res, next) =\u003e {\n  try {\n    const { id } = req.params;\n    if (cache.has(id)) {\n      return res.status(200).json(cache.get(id));\n    }\n    return next();\n  } catch (err) {\n    throw new Error(err);\n  }\n};\n\napp.get(\"/\", (req, res) =\u003e {\n  return res.json({ message: \"Hello World\" });\n});\n\n/**\n * GET ToDo Items\n */\napp.get(\"/todos/:id\", verifyCache, async (req, res) =\u003e {\n  try {\n    const { id } = req.params;\n    const { data } = await axios.get(`https://jsonplaceholder.typicode.com/todos/${id}`);\n    cache.set(id, data);\n    return res.status(200).json(data);\n  } catch ({ response }) {\n    return res.sendStatus(response.status);\n  }\n});\n\napp.listen(3000, function () {\n  console.log(`App listening at http://localhost:3000/`);\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to implement caching using Redis in Node.js?\n\nRedis is an open-source (BSD licensed), in-memory data structure store used as a database, cache, and message broker. Redis also supports disk-persistent data storage.\n\nIts key-value data storage system is another plus because it makes storage and retrieval much simpler. Using Redis, we can store and retrieve data in the cache using the SET and GET methods, respectively.\n\n**Installation:**\n\n```js\nnpm install -save redis\n```\n\n**Example:**\n\n```js\nconst express = require(\"express\");\nconst axios = require(\"axios\");\nconst redis = require(\"redis\");\nconst app = express();\n\nconst client = redis.createClient(6379);\n\nclient.on(\"error\", (error) =\u003e {\n  console.error(error);\n});\n\napp.get(\"/\", (req, res) =\u003e {\n  return res.json({ message: \"Hello World\" });\n});\n\nconst cache = (req, res, next) =\u003e {\n  try {\n    const { id } = req.params;\n    client.get(id, (error, result) =\u003e {\n      if (error) throw error;\n      if (result !== null) {\n        return res.json(JSON.parse(result));\n      } else {\n        return next();\n      }\n    });\n  } catch (err) {\n    throw new Error(err);\n  }\n};\n\napp.get(\"/todos/:id\", cache, async (req, res) =\u003e {\n  try {\n    const { id } = req.params;\n    const data = await axios.get(`https://jsonplaceholder.typicode.com/todos/${id}`);\n    client.set(id, JSON.stringify(data), \"ex\", 15);\n    return res.status(200).json(data);\n  } catch ({ response }) {\n    return res.sendStatus(response.status);\n  }\n});\n\napp.listen(3000, function () {\n  console.log(`App listening at http://localhost:3000/`);\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to implement Memcached in Node.js?\n\n**Memcached** is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read. Memcached is free and open-source software, licensed under the Revised BSD licence. Memcached runs on Unix-like operating systems (at least LINUX and OS X) and on Microsoft windows.\n\nWe can store data to memcached server in key pair format. So whenever any request come from the app can be matched with memcached server without any query from mysql/Nosql server. This increases the performance of the application.\n\n**Installation:**\n\n```js\nnpm install memcached\n```\n\n**Setting up the client:**\n\nThe constructor of the memcached client take 2 different arguments server locations and options. Syntax:\n\n```js\nconst Memcached = require('memcached');\nconst memcached = new Memcached(Server locations, options);\n```\n\n**Example:**\n\n```js\n/**\n * Memcached\n */\nconst Memcached = require('memcached');\n// all global configurations should be applied to the .config object of the Client.\nMemcached.config.poolSize = 25;\n\nconst memcached = new Memcached('localhost:11211', { retries:10, retry:10000, remove:true, failOverServers:['192.168.0.103:11211']});\n```\n\n\u003cbr/\u003e\n\n**Reference:**\n\n* *[https://www.npmjs.com/package/memcached](https://www.npmjs.com/package/memcached)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 14. NODE.JS ERROR HANDLING\n\n\u003cbr/\u003e\n\n## Q. What is the preferred method of resolving unhandled exceptions in Node.js?\n\nUnhandled exceptions in Node.js can be caught at the Process level by attaching a handler for uncaughtException event.\n\n```js\nprocess.on('uncaughtException', function(err) {\n    console.log('Caught exception: ' + err);\n});\n```\n\nProcess is a global object that provides information about the current Node.js process. Process is a listener function that is always listening to events.\n\nFew events are :\n\n1. Exit\n1. disconnect\n1. unhandledException\n1. rejectionHandled\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Error Handling in Node.js?\n\nAn error is any problem given out by the program due to a number of factors such as logic, syntax, timeout, etc. An error in Node.js is any instance of the Error object. Common examples include built-in error classes, such as ReferenceError, RangeError, TypeError, URIError, EvalError, and SyntaxError.\n\nUser-defined errors can also be created by extending the base Error object, a built-in error class, or another custom error. In general, Node.js errors are divided into two distinct categories: operational errors and programmer errors.\n\n**1. Operational Errors:**\n\nOperational errors represent runtime problems. These errors are expected in the Node.js runtime and should be dealt with in a proper way. Here\\'s a list of common operational errors:\n\n* failed to connect to server\n* failed to resolve hostname\n* invalid user input\n* request timeout\n* server returned a 500 response\n* socket hang-up\n* system is out of memory\n\n**2. Programmer Errors:**\n\nProgrammer errors are what we call bugs. They represent issues in the code itself. Here\\'s a common one for Node.js, when you try reading a property of an undefined object. It\\'s a classic case of programmer error. Here are a few more:\n\n* called an asynchronous function without a callback\n* did not resolve a promise\n* did not catch a rejected promise\n* passed a string where an object was expected\n* passed an object where a string was expected\n* passed incorrect parameters in a function\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain Error Handling approaches in Node.js?\n\n**1. Using try-catch block:**\n\nTry-catch declaration is basically used to handle runtime errors in node.js. If the code in the try block throws an exception, the code in the catch block will be executed. It can be extended using finally clause. The finally clause is statements that are executed after the try statement completes.\n\n**Example:**\n\n```js\nfunction square(num) {\n  if (typeof num !== \"number\") {\n    throw new TypeError(`Expected number but got: ${typeof num}`);\n  }\n\n  return num * num;\n}\n\ntry {\n  square(\"10\");\n} catch (err) {\n  console.log(err.message); // Expected number but got: string\n}\n```\n\n**2. Using promises:**\n\nPromise in Node.js is a contemporary way to handle errors, and it is usually preferred compared to callbacks. In the function, we will return a promise, which is a wrapper to our primary logic. We pass two arguments while defining the Promise object:\n\n* resolve — used to resolve promises and provide results\n* reject — used to report/throw errors\n\n**Example:**\n\n```js\nfunction square(num) {\n  return new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n      if (typeof num !== \"number\") {\n        reject(new TypeError(`Expected number but got: ${typeof num}`));\n      }\n\n      const result = num * num;\n      resolve(result);\n    }, 100);\n  });\n}\n\nsquare(\"10\")\n  .then((result) =\u003e console.log(result))\n  .catch((err) =\u003e console.error(err));\n```\n\nOutput:\n\n```js\nTypeError: Expected number but got: string\n    at Timeout._onTimeout (C:\\node\\index.js:5:16)\n    at listOnTimeout (internal/timers.js:554:17)\n    at processTimers (internal/timers.js:497:7)\n```\n\n**3. Error-first callbacks:**\n\nNode.js uses an error-first callback convention in most of its asynchronous methods to ensure that errors are checked properly before the results of an operation are used. This callback function is usually the last argument to the function that initiates an asynchronous operation, and it is called once when an error occurs or a result is available from the operation.\n\n**Example:**\n\n```js\nconst fs = require('fs');\n\nfs.readFile('/path/to/file.txt', (err, result) =\u003e {\n  if (err) {\n    console.error(err);\n    return;\n  }\n\n  // Log the file contents if no error\n  console.log(result);\n});\n```\n\nOutput\n\n```js\n[Error: ENOENT: no such file or directory, open 'D:\\path\\to\\file.txt'] {\n  errno: -4058,\n  code: 'ENOENT',\n  syscall: 'open',\n  path: 'D:\\\\path\\\\to\\\\file.txt'\n}\n```\n\n**4. Using the async/await approach:**\n\nAsync/await is just syntactic sugar that is meant to augment promises. It provides a synchronous structure to asynchronous code.\nThe return value of an async function is a Promise. The await waits for the promise to be resolved or rejected.\n\n```js\nconst fs = require('fs');\nconst util = require('util');\n\nconst readFile = util.promisify(fs.readFile);\n\nconst read = async () =\u003e {\n  try {\n    const result = await readFile('/path/to/file.txt');\n    console.log(result);\n  } catch (err) {\n    console.error(err);\n  }\n};\n\nread();\n```\n\nOutput:\n\n```js\n[Error: ENOENT: no such file or directory, open 'D:\\path\\to\\file.txt'] {\n  errno: -4058,\n  code: 'ENOENT',\n  syscall: 'open',\n  path: 'D:\\\\path\\\\to\\\\file.txt'\n}\n```\n\n**5. Use Middleware:**\n\nIt is usually a good idea to build a centralized error-handling component in order to avoid possible code duplications when handling errors. The error-handling component is in charge of making the caught errors understandable by, for example, sending notifications to system admins (if necessary), transferring events to a monitoring service like Sentry.io, and logging them.\n\nIt is a good decision to employ a customizable logger like winston or morgan. Here is a customized winston logger:\n\n**Example:**\n\n```js\nconst winston = require(\"winston\");\n\nconst logger = winston.createLogger({\n  level: \"debug\",\n  format: winston.format.json(),\n  transports: [new winston.transports.Console()],\n});\n\nmodule.exports = logger;\n```\n\n```js\nconst express = require(\"express\");\nconst logger = require(\"./logger\");\nconst app = express();\n\napp.get(\"/event\", (req, res, next) =\u003e {\n  try {\n    throw new Error(\"Not User!\");\n  } catch (error) {\n    logger.error(\"Events Error: Unauthenticated user\");\n    res.status(500).send(\"Error!\");\n  }\n});\n\napp.listen(3000, () =\u003e {\n  logger.info(\"Server Listening On Port 3000\");\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to solve \"Process out of Memory Exception\" in Node.js?\n\nProcess out of Memory Exception is an exception that occurs when your node.js program gets out of memory. This happens when the default memory allocated to our program gets exceeded by our program while execution.\n\nThis exception can be solved by increasing the default memory allocated to our program to the required memory by using the following command.\n\n**Syntax:**\n\n```js\nnode --max-old-space-size=\u003cNEW_SIZE_IN_MB\u003e index.js\n```\n\n**Example:**\n\n```js\n/**\n * OutOfMemory Exception\n */\nlet items = [];\n\nfor (let i = 0; i \u003c 999999999; i++) {\n  items.push(i);\n}\n\nconsole.log(items);\n```\n\nOutput:\n\n```js\n\u003c--- Last few GCs ---\u003e\n\n[11652:000001DA4373BE50]      581 ms: Scavenge 765.9 (799.0) -\u003e 765.9 (799.0) MB, 29.6 / 0.0 ms  (average mu = 1.000, current mu = 1.000) allocation failure    \n[11652:000001DA4373BE50]      844 ms: Scavenge 1148.4 (1181.6) -\u003e 1148.4 (1181.6) MB, 44.7 / 0.0 ms  (average mu = 1.000, current mu = 1.000) allocation failure\n\n[11652:000001DA4373BE50]     1239 ms: Scavenge 1722.2 (1755.4) -\u003e 1722.2 (1755.4) MB, 67.5 / 0.0 ms  (average mu = 1.000, current mu = 1.000) allocation failure\n\n\n\u003c--- JS stacktrace ---\u003e\n\nFATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory\n 1: 00007FF784AA052F napi_wrap+109311\n 2: 00007FF784A45256 v8::internal::OrderedHashTable\u003cv8::internal::OrderedHashSet,1\u003e::NumberOfElementsOffset+33302\n 3: 00007FF784A46026 node::OnFatalError+294\n 4: 00007FF78531163E v8::Isolate::ReportExternalAllocationLimitReached+94\n 5: 00007FF7852F64BD v8::SharedArrayBuffer::Externalize+781\n 6: 00007FF7851A094C v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1516\n 7: 00007FF7851C547F v8::internal::Factory::NewUninitializedFixedArray+111\n 8: 00007FF78508B3C0 v8::Object::GetIsolate+8128\n 9: 00007FF784F151F7 v8::internal::interpreter::JumpTableTargetOffsets::iterator::operator=+169671\n10: 00007FF785399FED v8::internal::SetupIsolateDelegate::SetupHeap+463949\n11: 000003EC8D443246\n```\n\nThe default memory allocated to a node.js program is 512MB on 32-bit systems and 1024MB on 64-bit systems. In the below example, we have increased the memory space requirements to 2048MB or 2GB. Use the following command to run the JS file(index.js).\n\n**Example:**\n\n```js\nnode --max-old-space-size=2048 index.js\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the types of memory leaks in node.js?\n\nA memory leak is a condition that occurs when a program doesn\\'t release the memory it allocates. For instance, the system assigns memory locations to store values for the variables that we declare inside our program.\n\nHigh-level programming languages such as JavaScript utilize automatic memory management, known as garbage collection. Garbage collection allocates the memory to a variable once we declare it and reclaims the memory once it is no longer needed. Unfortunately, even though JavaScript uses a garbage collector to release the memory, sometimes determining whether to free the memory or not is undecidable.\n\nThe common causes of Memory Leaks in Node.JS are:\n\n**1. Global variables:**\n\nThis is one of the most common causes of leaks in Node. Due to the nature of JavaScript as a language, it is very easy to add to global variables and resources. If these are not cleaned over time, they keep adding up and eventually crash the application.\n\n**Example:**\n\n```js\nconst http = require(\"http\");\n\nconst requestLogs = []; // causing the memory leak\nconst server = http.createServer((req, res) =\u003e {\n    requestLogs.push({ url: req.url, array: new Array(10000).join(\"*\")\n    res.end(JSON.stringify(requestLogs));\n});\n\nserver.listen(3000);\nconsole.log(\"Server listening to port 3000. Press Ctrl+C to stop it.\");\n```\n\n**2. Closures:**\n\nClosures memorize their surrounding context. When a closure holds a reference to a large object in heap, it keeps the object in memory as long as the closure is in use.\n\nThis implies easily ending up in situations where a closure holding such a reference can be improperly used leading to a memory leak.\n\n**3. Timers \u0026 Events:**\n\nThe use of setTimeout, setInterval, Observers, and event listeners can cause memory leaks when heavy object references are kept in their callbacks without proper handling.\n\n**4. Multiple references:**\n\nIf you reference the same object from multiple objects, it can lead to a memory leak if one of the references is garbage collected while the other one is left dangling.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to prevent memory leaks in Node.js?\n\nTools to help debug memory leaks:\n\n**1. Node-heapdump:**\n\nThe node-heapdump module is good for post-mortem debugging. It generates heap dumps on your SIGUSR2. To help catch bugs easily in a development environment, add node-heapdump as a dependency to your project like so:\n\n```js\nconst heapdump = require(\"heapdump\");\n\nheapdump.writeSnapshot(function (err, filename) {\n  console.log(\"Sample dump written to\", filename);\n});\n```\n\n**2. Clinic.js:**\n\nClinic.js is a handy toolset to diagnose and pinpoint performance bottlenecks in your Node applications. The Clinic.js HeapProfiler uses flame graphs to highlight memory allocations. You can use it with tools such as AutoCannon to simulate HTTP load when profiling.\n\n**3. The process.memoryUsage method:**\n\nThe process.memoryUsage method provides a simple way of monitoring memory usage in your Node applications.\n\nThe method returns an object with the following properties:\n\n* **rss:**, or resident set size, refers to the amount of space occupied in the main memory for the process, which includes code segment, heap, and stack. If your RSS is going up, there is a likelihood your application is leaking memory\n* **heapTotal:**, the total amount of memory available for JavaScript objects\n* **heapUsed:**, the total amount of memory occupied by JavaScript objects\n* **external:**, the amount of memory consumed by off-heap data (buffers) used by Node; this is where objects, strings, and closures are stored\n* **arrayBuffers:**, the amount of memory allocation for ArrayBuffers and SharedArrayBuffers (the external memory size also includes this memory value)\n\n**Example:**\n\n```js\nconsole.log(process.memoryUsage());\n```\n\nOutput:\n\n```js\n{\n  rss: 4935680,\n  heapTotal:1826816,\n  heapUsed:650472,\n  external: 49879,\n  arrayBuffers: 17310,\n}\n```\n\n**4. Node Inspector:**\n\nNode Inspector is a debugger interface for Node applications. Run Node with the --inspect flag to use it, and it starts listening for a debugging client. It is one of the simplest ways of capturing heap snapshots with Chrome DevTools.\n\n**5. Chrome DevTools:**\n\nChrome offers a range of tools to help debug your memory and performance issues, including allocation timelines, sampling heap profiler, and heap snapshots etc.\n\n## Q. How Garbage collection works in Node.JS?\n\nThe V8 uses a scheme similar to the Java Virtual Machine and divides the memory into segments. The thing that wraps the scheme concept is known as Resident Set, which refers to the portion of memory occupied by a process that is held in the RAM.\n\n* **Stack**: Stores static data, method and function frames, primitive values, and pointers to stored objects. The stack is managed by the operating system.\n\n* **Heap**: Stores objects. Because everything in JavaScript is an object this means all dynamic data like arrays, closures, etc. The heap is the biggest block of memory and it\\'s where Garbage Collection (GC) happens.\n\n* **Code Segment**: the actual code is being executed.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/memory-scheme.png\" alt=\"Memory Segments\" width=\"200px\"/\u003e\n\u003c/p\u003e\n\nGarbage collection frees up memory in the Heap used by objects that are no longer referenced from the Stack, either directly or indirectly. The goal is to create free space for creating new objects. Garbage collection is generational. Objects in the Heap are grouped by age and cleared at different stages.\n\n**Mark-and-sweep algorithm:**\n\nIn JavaScript, the root is the global object. The garbage collector start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 15. NODE.JS LOGGING\n\n\u003cbr/\u003e\n\n## Q. How to debug an application in Node.js?\n\n**1. node-inspector:**\n\n```js\nnpm install -g node-inspector\n```\n\nRun\n\n```js\nnode-debug app.js\n```\n\n**2. Debugging:**\n\n* Debugger\n* Node Inspector\n* Visual Studio Code\n* Cloud9\n* Brackets\n\n**3. Profiling:**\n\n```js\n1. node --prof ./app.js\n2. node --prof-process ./the-generated-log-file\n```\n\n**4. Heapdumps:**\n\n* node-heapdump with Chrome Developer Tools\n\n**5. Tracing:**\n\n* Interactive Stack Traces with TraceGL\n\n**6. Logging:**\n\nLibraries that output debugging information\n\n* Caterpillar\n* Tracer\n* scribbles\n\nLibraries that enhance stack trace information  \n\n* Longjohn\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 16. NODE.JS INTERNATIONALIZATION\n\n\u003cbr/\u003e\n\n#### Q. How to use locale (i18n) in Node.js?\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 17. NODE.JS TESTING\n\n\u003cbr/\u003e\n\n## Q. What is a stub?\n\nStubbing and verification for node.js tests. Enables you to validate and override behaviour of nested pieces of code such as methods, require() and npm modules or even instances of classes. This library is inspired on node-gently, MockJS and mock-require.  \n\n**Features of Stub:**  \n\n* Produces simple, lightweight Objects capable of extending down their tree\n* Compatible with Nodejs\n* Easily extendable directly or through an ExtensionManager\n* Comes with predefined, usable extensions\n\nStubs are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made during test cases. Also, you can assert on with what these stubs were called.\n\nA use-case can be a file read, when you do not want to read an actual file:\n\n```js\nconst fs = require('fs');\n\nconst readFileStub = sinon.stub(fs, 'readFile', function (path, cb) {  \n  return cb(null, 'filecontent');\n});\n\nexpect(readFileStub).to.be.called;  \nreadFileStub.restore();\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a test pyramid?\n\nThe \"Test Pyramid\" is a metaphor that tells us to group software tests into buckets of different granularity. It also gives an idea of how many tests we should have in each of these groups. It shows which kinds of tests you should be looking for in the different levels of the pyramid and gives practical examples on how these can be implemented.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/testPyramid.png\" alt=\"Test Pyramid\" /\u003e\n\u003c/p\u003e\n\nMike Cohn\\'s original test pyramid consists of three layers that your test suite should consist of (bottom to top):\n\n1. Unit Tests\n1. Service Tests\n1. User Interface Tests\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to use Joi module for schema validation in Node.js?\n\nJoi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data.\n\n**Example:**\n\n```js\nconst Joi = require(\"joi\");\n\n// User-defined function to validate the user\n\nfunction validateUser(user) {\n\n  const JoiSchema = Joi.object({\n\n    username: Joi.string().min(5).max(30).required(),\n\n    email: Joi.string().email().min(5).max(50).optional(),\n\n    date_of_birth: Joi.date().optional(),\n\n    account_status: Joi.string()\n      .valid(\"activated\")\n      .valid(\"unactivated\")\n      .optional(),\n  }).options({ abortEarly: false });\n\n  return JoiSchema.validate(user);\n}\n\nconst user = {\n  username: \"Deepak Lucky\",\n  email: \"deepak.lucky@gmail.com\",\n  date_of_birth: \"2000-07-07\",\n  account_status: \"activated\",\n};\n\nlet response = validateUser(user);\n\nif (response.error) {\n  console.log(response.error.details);\n} else {\n  console.log(\"Validated Data\");\n}\n```\n\n**\u0026#9885; [Try this example on CodeSandbox](https://codesandbox.io/s/schema-validation-using-joi-s2nhzs)**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 18. NODE.JS MISCELLANEOUS\n\n\u003cbr/\u003e\n\n## Q. How to improve Node.js performance?\n\n**1. Asynchronous Functions:**\n\nUsing asynchronous functions in an application that heavily uses I/O operations will improve it. This is because the CPU will be able to handle multiple requests simultaneously due to non-blocking I/O, while one of these requests is making an Input/Output operation.\n\n**Example:**\n\n```js\nvar fs = require('fs');\n\n// Performing a blocking I/O\nvar file = fs.readFileSync('/etc/file.txt');\nconsole.log(file);\n\n// Performing a non-blocking I/O\nfs.readFile('/etc/file.txt', function(err, file) {\n    if (err) return err;\n    console.log(file);\n});\n```\n\n**2. Query Optimization:**\n\nBasic tips to improve your database performance/optimization overview\n\n* **Indexing** - Indexing is an approach to optimize the performance of a database by minimizing the number of disk accesses required when a query is processed.\n\n* **Avoid SELECT** -  Use the SELECT statement to query only the data you need and avoid extra fetching loads to your database.\n\n```sql\n-- query1\nSELECT * FROM Customers\n\n-- query2 (optimized)\nSELECT FirstName, LastName, Address, City, State, Zip FROM Customers\n```\n\n* **Use LIMIT** - LIMIT will return only the specified number of records.\n\n```sql\nSELECT FirstName, LastName, Address, City, State, Zip FROM Customers LIMIT 100\n```\n\n* **Wildcard (%)** - Use wildcard (%) character appropriately\n\n```sql\n-- SELECT customers whose first names start with \"Avi\"\n\n-- query1\nSELECT FirstName from Customers where FirstName like '%avi%'\n\n-- query2 (optimized)\nSELECT FirstName from Customers where FirstName like 'avi%'\n```\n\n**3. Caching:**\n\nCaching is one of the common ways of improving the Node Js performance. A cache is a memory buffer where frequently accessed data is temporarily stored to be accessed quicker. Cached data is then retrieved without having to access the origin. Caching will improve your app response time and even reduce some costs such as bandwidth and data volumes.\n\n* **Redis cache** is entirely asynchronous with optimal performance to handle cached data requests in a single thread.\n\n* **Memcached** stores data across different nodes. It uses a hashing schema that provides a hash table functionality. These ensure that adding, or removing a server node does not significantly change the mapping of the keys to server nodes.\n\n* **Node-cache** works almost like Memcached with the set, get, and delete methods. It has a timeout that deletes data from the cache when the timeout expires.\n\n* **Nginx** will help maintain load balance. Nginx will help cache static files, that will drastically offload the work of the application server. It offers low memory usage and high concurrency.\n\n**4. Load Balancing:**\n\nIt\\'s a typical challenge to create performant applications that can handle a huge number of incoming connections. Load balancing is the term for this method. The cluster module to allow load balancing and distribute incoming connections across all workers in an environment\\'s numerous CPU cores using a **round-robin** technique.\n\nUsing the PM2 process manager to keep applications alive indefinitely is another option. PM2 includes a cluster feature that allows you to run numerous processes over all cores without having to worry about changing the code to use the native cluster module.\n\n**5. Real-time Monitoring:**\n\nGauging the current level of performance of an application may require running different kinds of tests, such as the following:\n\n* **Load testing:** refers to the practice of simulating the expected usage of a system and measuring its response as the workload increases.\n\n* **Stress testing:** designed to measure how a system performs beyond the limits of normal working conditions. Its goal is to determine how much the system can handle before it fails and how it attempts to recover from a failure.\n\n* **Spike testing:** helps to test the behavior of an application when it receives a drastic increase or decrease in load.\n\n* **Scalability testing:** used to find the point at which the application stops scaling and identify the reasons behind it.\n\n* **Volume testing:** determines if a system can cope with large amounts of data.\n\n* **Endurance testing:** helps evaluate the behavior of a software application under sustained load for a long period, to catch problems such as memory leaks.\n\n**6. Use HTTP/2:**\n\nThe HTTP/2 in a Node.js application make web browsing faster and easier while reducing bandwidth usage. HTTP/2 is aimed at increasing performance and addressing concerns with HTTP/1.x.\n\nHTTP/2 has the following features:\n\n* **Header Compression** - This disables unnecessary headers and compels all HTTP headers to be sent compressed.\n* **Multiplexing** - This allows multiple requests to simultaneously retrieve resources and response messages over a single TCP connection.\n\n**7. Stateless Authentication:**\n\nStateless authentication on the client-side with the help of JSON Web Token ( **JWT** ) provides great speed to the application. In this Stateless Authentication procedure, a web token is created whenever the user login into the website. It contains all the required user information, which is sent back to the respective user for authenticating all API requests.\n\n**8. Module bundlers and task runners:**\n\nModule bundlers are build tools for processing groups of modules and their dependencies into a file or group of files. This especially includes images, JavaScript, and CSS files. The process that makes this possible involves module bundlers (e.g., webpack, Parcel, Rollup) and task runners (e.g., Gulp, Grunt, etc.).\n\nThis allows for complex transforms, such as shortening multicharacter variable names or using a shorter syntax that\\'s equivalent to the original code and combining several JavaScript files into one to reduce the number of network requests.\n\n**9. Script Tracing and Logging:**\n\nLogging helps track your application activities and traffic. When an app is running, it is possible to get fatal errors (even though your app was running properly after production testing).\n\nCommonly used methods for logging in Node.js are\n\n* **Winston** -  is a multi-transport async logger, which is simple, universal, and extremely versatile. It makes logging more flexible and extensible. It is the most popular logger based on NPM stats. Winston has different transports with different default levels that indicate message priority. These levels include ( error, warn, info, http, verbose, debug, silly )\n\n* **Morgan** - Morgan is an HTTP request logger middleware for Node.js applications. Morgan gives insight on how your app is being used and alerts you on potential errors and issues that could be threats to your application.\n\n**Example:**\n\n```js\nconst express = require('express')\nconst fs = require('fs')\nconst morgan = require('morgan')\nconst path = require('path')\n \nconst app = express()\n \n// create a write stream (in append mode)\nconst accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })\n \n// setup the logger\napp.use(morgan('combined', { stream: accessLogStream }))\n \napp.get('/', function (req, res) {\n  res.send('hello, world!')\n})\n```\n\n**10. Gzip Compression:**\n\nGzip compresses HTTP requests and responses. Gzip compresses responses before sending them to the browser, thus, the browser takes a shorter time to fetch them. Gzip also compresses the request to the remote server, which significantly increases web performance.\n\n**Example:**\n\n```js\nconst compression = require(\"compression\");\nconst express = require(\"express\");\nconst app = express();\n\n// compress all responses\napp.use(compression());\n// ...\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is crypto in Node.js?\n\nThe Node.js Crypto module supports cryptography. It provides cryptographic functionality that includes a set of wrappers for open SSL\\'s hash HMAC, cipher, decipher, sign and verify functions.\n\n* **Hash**: A hash is a fixed-length string of bits i.e. procedurally and deterministically generated from some arbitrary block of source data.\n* **HMAC**: HMAC stands for Hash-based Message Authentication Code. It is a process for applying a hash algorithm to both data and a secret key that results in a single final hash.\n\n* Encryption Example using Hash and HMAC\n\n```js\nconst crypto = require('crypto');  \nconst secret = 'abcdefg';  \nconst hash = crypto.createHmac('sha256', secret)  \n                   .update('Welcome to Node.js')  \n                   .digest('hex');  \nconsole.log(hash);  \n```\n\n* Encryption example using Cipher\n\n```js\nconst crypto = require('crypto');  \nconst cipher = crypto.createCipher('aes192', 'a password');  \n\nconst encrypted = cipher.update('Hello Node.js', 'utf8', 'hex');  \nencrypted += cipher.final('hex');  \n\nconsole.log(encrypted);\n```\n\n* Decryption example using Decipher\n\n```js\nconst crypto = require('crypto');  \nconst decipher = crypto.createDecipher('aes192', 'a password');  \n\nconst encrypted = '4ce3b761d58398aed30d5af898a0656a3174d9c7d7502e781e83cf6b9fb836d5';  \nconst decrypted = decipher.update(encrypted, 'hex', 'utf8');  \ndecrypted += decipher.final('utf8');  \n\nconsole.log(decrypted);  \n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to execute an external program from within Node.js?\n\n```js\nconst { exec } = require('child_process');\n\nexec('\"/path/to/test file/test.sh\" arg1 arg2');\n\nexec('echo \"The \\\\$HOME variable is $HOME\"');\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is REPL?\n\nREPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell (Unix/Linux) and command prompt. Node comes with the REPL environment when it is installed. System interacts with the user through outputs of commands/expressions used. It is useful in writing and debugging the codes. The work of REPL can be understood from its full form:\n\n* **Read**: It reads the inputs from users and parses it into JavaScript data structure. It is then stored to memory.\n* **Eval**: The parsed JavaScript data structure is evaluated for the results.\n* **Print**: The result is printed after the evaluation.\n* **Loop**: Loops the input command. To come out of NODE REPL, press ctrl+c twice\n\nSimple Expression\n\n```js\n$ node\n\u003e 10 + 20\n30\n\u003e 10 + ( 20 * 30 ) - 40\n570\n\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What does the runtime environment mean in Node.js?\n\nThe Node.js runtime is the software stack responsible for installing your web service\\'s code and its dependencies and running your service.\n\nThe Node.js runtime for App Engine in the standard environment is declared in the `app.yaml` file:\n\n```js\nruntime: nodejs10\n```\n\nThe 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain usage of NODE_ENV?\n\nNODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value.\n\nFor example, when we work on a project and there are production and development environments. We don\\'t need to use caching in the development env. So we set\n\n ```js\n NODE_ENV=development\n ```\n\nand use the code below\n\n```js\nif (process.env.NODE_ENV === 'development')\n    useCaching = false;\n```\n\nUpon that, if the project runs on production it will use caching.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How assert works in Node.js?\n\nThe assert module provides a way of testing expressions. If the expression evaluates to 0, or false, an assertion failure is being caused, and the program is terminated.\n\nThis module was built to be used internally by Node.js.\n\n```js\n// Sample usage\n\nconst assert = require('assert');\nassert(50 \u003e 70, \"50 is less than 70.\");\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the use of DNS module in Node.js?\n\nDNS is a node module used to do name resolution facility which is provided by the operating system as well as used to do an actual DNS lookup. No need for memorising IP addresses – DNS servers provide a nifty solution of converting domain or subdomain names to IP addresses. This module provides an asynchronous network wrapper and can be imported using the following syntax.\n\n```js\nconst dns = require('dns');\n```\n\n**Example:** `dns.lookup()` function  \n\n```js\nconst dns = require('dns');  \ndns.lookup('www.google.com', (err, addresses, family) =\u003e {  \n  console.log('addresses:', addresses);  \n  console.log('family:',family);  \n});  \n```\n\n**Example:** `resolve4()` and `reverse()` functions\n\n```js\nconst dns = require('dns');  \ndns.resolve4('www.google.com', (err, addresses) =\u003e {  \n  if (err) throw err;  \n  console.log(`addresses: ${JSON.stringify(addresses)}`);  \n  addresses.forEach((a) =\u003e {  \n    dns.reverse(a, (err, hostnames) =\u003e {  \n      if (err) {  \n        throw err;  \n      }  \n      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);  \n    });  \n  });  \n});\n```\n\n**Example:** Print the localhost name using `lookupService()` function\n\n```js\nconst dns = require('dns');  \ndns.lookupService('127.0.0.1', 22, (err, hostname, service) =\u003e {  \n  console.log(hostname, service);  \n    // Prints: localhost  \n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is JIT and how is it related to Node.js?\n \nNode.js has depended on the V8 JavaScript engine to provide code execution in the language. The V8 is a JavaScript engine built at the google development center, in Germany. It is open source and written in C++. It is used for both client side (Google Chrome) and server side (node.js) JavaScript applications. A central piece of the V8 engine that allows it to execute JavaScript at high speed is the JIT (Just In Time) compiler. This is a dynamic compiler that can optimize code during runtime. When V8 was first built the JIT Compiler was dubbed FullCodegen. Then, the V8 team implemented Crankshaft, which included many performance optimizations that FullCodegen did not implement.\n\nThe `V8` was first designed to increase the performance of the JavaScript execution inside web browsers. In order to obtain speed, V8 translates JavaScript code into more efficient machine code instead of using an interpreter. It compiles JavaScript code into machine code at execution by implementing a JIT (Just-In-Time) compiler like a lot of modern JavaScript engines such as SpiderMonkey or Rhino (Mozilla) are doing. The main difference with V8 is that it doesn\\'t produce bytecode or any intermediate code.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to generate and verify checksum of the given string in Nodejs\n\nThe **checksum** (aka **hash sum**) calculation is a one-way process of mapping an extensive data set of variable length (e.g., message, file), to a smaller data set of a fixed length (hash). The length depends on a hashing algorithm.\n\nFor the checksum generation, we can use node `crypto()` module. The module uses `createHash(algorithm)` to create a checksum (hash) generator. The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform.\n\n**Example:**\n\n```js\nconst crypto = require('crypto');\n\n// To get a list of all available hash algorithms\ncrypto.getHashes() // [ 'md5', 'sha1', 'sha3-256', ... ]\n\n  \n// Create hash of SHA1 type\nconst key = \"MY_SECRET_KEY\";\n\n\n// 'digest' is the output of hash function containing  \n// only hexadecimal digits\nhashPwd = crypto.createHash('sha1').update(key).digest('hex');\n  \nconsole.log(hashPwd); //ef5225a03e4f9cc953ab3c4dd41f5c4db7dc2e5b\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to gracefully shutdown Node.js Server?\n\nThe graceful shutdown of our application indicates when all of the resources it used and all of the traffic and/or data processing what it handled are closed and released properly. It means that no database connection remains open and no ongoing request fails because we stop our application.\n\nPossible scenarios for a graceful web server shutdown:\n\n* Handle process kill signal\n* Stop new requests from client\n* Close all data process\n* Exit from process\n\n**Example:**\n\n```js\nfunction shutdown() {\n  server.close(function onServerClosed(err) {\n    if (err) {\n      console.error(err);\n      process.exit(1);\n    }\n\n    closeMyResources(function onResourcesClosed(err) {\n      // error handling\n      process.exit();\n    });\n  });\n}\n\nprocess.on(\"SIGTERM\", function onSigterm() {\n  console.info(\"Got SIGTERM. Graceful shutdown start\",  new Date().toISOString());\n  // start graceul shutdown here\n  shutdown();\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What kind of web application should never be built by using Node.js?\n\nNode.js development has many benefits, but it won\\'t provide the best performance for some application\\'s needs or processes. Here are the points for which developers or businesses must avoid Node.js:\n\n**1. A CPU-Heavy Application:**\n\nNode.js uses an event-based, non-blocking I/O architecture and only has one CPU – all of that intensive CPU processing would block incoming requests. As a result of the high-end number crunching, the thread might get stuck.\n\n**2. A Relational Database-Backed Server-Side App:**\n\nYou can also develop a standard web application on the server using Node.js and express.js. However, the responsiveness of Node.js will be hampered if these web applications consume a lot of CPU power. Because Node.js Relational DB tool is still in beta, it\\'s best to use other environments to conduct relational operations.\n\n**3. Developing simple CRUD application:**\n\nYou can use Node.js for such applications, but the performance and power for which Node.js is known would remain useless. Hence, it is strongly recommended to go for other frameworks or environments for developing simple HTML application instead of Node.js.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the types of applications you can build with Node.js?\n\nNode.js is a JavaScript runtime environment built upon event-driven programming that enables non-blocking I/O (Input/Output) capable of serving multiple concurrent events in a single thread. Non-blocking I/O makes Node.js very fast, lightweight, scalable, and efficient in handling data-heavy and I/O-heavy workloads characteristic of several types of web applications.\n\nTypes of applications you can build with Node.js\n\n* IoT (Internet of Things)\n* Real-Time Chat Application\n* Single-Page Application\n* Social Media Platform\n* Streaming App\n* Online Payment Processor\n* Remote Collaboration Tool\n* CRM Tool\n* Advanced Fintech App\n* Content Management System\n* E-Learning Platform\n* E-Commerce Platform\n* Ridesharing App\n* Project Management Tools\n* Location-Based App\n* Online Publishing Platforms\n* ERP Tool\n* Websites With Server-Side Rendering\n* FastCGI Servers\n* Command Line Tools\n* API Servers\n* Desktop Apps\n* Backend for Mobile Apps\n* Server Management Services\n* Notification Centre\n* Custom DNS Server\n* Static Site Generator\n* Game Servers, Game Clients\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the use cases for the Node.js \"vm\" core module?\n\nThe \"VM\" module enables compiling and running code within V8 Virtual Machine contexts. JavaScript code can be compiled and run immediately or compiled, saved, and run later. It provides a way of executing JavaScript on a virtual machine.\n\nA common use case is to run the code in a different V8 Context. This means invoked code has a different global object than the invoking code.\n\n**Syntax:**\n\n```js\nconst vm = require('vm');\n```\n\n**VM Methods:**\n\n|Method            |Description                            |\n|------------------|---------------------------------------|\n|createContext()   |Prepares a virtual machine, or sandbox, where you can execute scripts|\n|isContext()       |Returns true if the specified sandbox has been created by the createContext() method|\n|runInContext()    |Executes JavaScript code in the specified context, and returns the result|\n|runInDebug()      |Executes JavaScript inside the debug context|\n|runInNewContext() |Executes JavaScript code in a new context, and returns the result|\n|runInThisContext()|Executes JavaScript code in the global context, and returns the result|\n\n**Example:**\n\n```js\nconst vm = require(\"vm\");\n\nconst x = 10;\nconst context = { x: 20 };\n\nvm.createContext(context); // Contextify the object.\n\nconst code = \"x += 10\";\n// Initially, x has the value 20 because that is the value of \"context.x\"\nvm.runInContext(code, context);\n\nconsole.log(context.x); // 30\nconsole.log(x); // 10\n```\n\n*Note: The vm module is not a security mechanism. Do not use it to run untrusted code.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n# Timing Function Execution in Node.js\n\nYou can check the runtime of a function in Node.js by using the `console.time()` and `console.timeEnd()` functions. Here's an example with an explanation:\n\n    ```javascript\n    function myFunction() {\n      console.log(\"Function started\");\n      \n      // Start the timer\n      console.time(\"myFunction\");\n    \n      // Simulate some time-consuming task\n      for (let i = 0; i \u003c 1000000000; i++) {\n        // Do some work\n      }\n    \n      // End the timer\n      console.timeEnd(\"myFunction\");\n    \n      console.log(\"Function ended\");\n    }\n    \n    myFunction();\n\n\n## In this example:\n\n- We use `console.log` to print a message indicating the start of the function.\n- We start a timer named \"myFunction\" using `console.time(\"myFunction\")`.\n- We simulate a time-consuming task by running a loop.\n- After the loop is finished, we end the timer using `console.timeEnd(\"myFunction\")`.\n- Finally, we use `console.log` to print a message indicating the end of the function.\n\n\n- Function started\n- myFunction: 5431.709ms\n- Function ended\n\nThe time in milliseconds (ms) represents the runtime of the function `myFunction`. You can use this approach to measure the runtime of specific parts of your code to identify performance bottlenecks or optimize your code.\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n\n#### Q. What is Distributed Denial of Service (DDoS) attacks and how to secure NodeJS REST API from it?\n#### Q. What are SOLID principles?\n#### Q. How to develop Node.js app using SOLID principles?\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Fnodejs-basics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearning-zone%2Fnodejs-basics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Fnodejs-basics/lists"}