{"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","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"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 secur","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"}