diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4a72db6..f4669b3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,7 +34,7 @@ Where: - Bug: For changes fixing a bug, typo or anything that leads to correctness of the system being worked on - Buggy: Should be avoided as much as possible but could be needed. It is used when changes have been partially implemented and execution of the current state of the project would lead to evil bugs and sinister errors. An example refers to unclosed tags and a hurried commit since you might not get access to your PC for a while. Projects with this commit type as the latest one should perhaps not be pulled or cloned except such implementation is to be continued by you. -- Message: refers to a message describing the changes made. It is important that each commit should only reflect one feature or implementation change. You should not cram two functionalities into one commit except they depend closely on one another. For example, implmentation of auth and adding views for a user profile are closely related but do not inter-depend on one another and should be separated into different commits. This is just to ensure a dev could work with states that are narrowed down to specific implementations and features. +- Message: refers to a message describing the changes made. It is important that each commit should only reflect one feature or implementation change. You should not cram two functionalities into one commit except they depend closely on one another. For example, implementation of auth and adding views for a user profile are closely related but do not inter-depend on one another and should be separated into different commits. This is just to ensure a dev could work with states that are narrowed down to specific implementations and features. ## FAQ diff --git a/README.md b/README.md index 5a36c4e..edb2139 100644 --- a/README.md +++ b/README.md @@ -1,217 +1,168 @@ -# Node.js Interview Questions +# Node.js Basics -*Click if you like the project. Pull Requests are highly appreciated.* +> *Click ★ if you like the project. Your contributions are heartily ♡ welcome.* -## Table of Contents +
-* *[NodeJS APIs](nodejs-api.md)* -* *[NodeJS Coding Practice](nodejs-programming.md)* -* *[NodeJS Commands](nodejs-commands.md)* +## Related Topics + +* *[HTML Basics](https://github.com/learning-zone/html-basics)* +* *[CSS Basics](https://github.com/learning-zone/css-basics)* +* *[JavaScript Basics](https://github.com/learning-zone/javascript-basics)* +* *[SQL Basics](https://github.com/learning-zone/sql-basics)* +* *[MongoDB Basics](https://github.com/learning-zone/mongodb-basics)* +* *[Node.js APIs](nodejs-api.md)* +* *[Node.js Commands](nodejs-commands.md)* +* *[Node.js Coding Practice](nodejs-programming.md)*
-| Sl.No| Questions | -|------|------------------| -| 01. |[What does the runtime environment mean in Node.js?](#q-what-does-the-runtime-environment-mean-in-nodejs)| -| 02. |[What is Node.js?](#q-what-is-nodejs)| -| 03. |[What is Node.js Process Model?](#q-what-is-nodejs-process-model)| -| 04. |[What are the data types in Node.js?](#q-what-are-the-data-types-in-nodejs)| -| 05. |[How to create a simple server in Node.js that returns Hello World?](#q-how-to-create-a-simple-server-in-nodejs-that-returns-hello-world)| -| 06. |[How do Node.js works?](#q-how-do-nodejs-works)| -| 07. |[What is an error-first callback?](#q-what-is-an-error-first-callback)| -| 08. |[What is callback hell in Node.js?](#q-what-is-callback-hell-in-nodejs)| -| 09. |[What are Promises in Node.js?](#q-what-are-promises-in-nodejs)| -| 10. |[What tools can be used to assure consistent style?](#q-what-tools-can-be-used-to-assure-consistent-style)| -| 11. |[When should you npm and when yarn?](#q-when-should-you-npm-and-when-yarn)| -| 12. |[What is a stub?](#q-what-is-a-stub)| -| 13. |[What is a test pyramid? How can you implement it when talking about HTTP APIs?](#q-what-is-a-test-pyramid-how-can-you-implement-it-when-talking-about-http-apis)| -| 14. |[How can you secure your HTTP cookies against XSS attacks?](#q-how-can-you-secure-your-http-cookies-against-xss-attacks)| -| 15. |[How can you make sure your dependencies are safe?](#q-how-can-you-make-sure-your-dependencies-are-safe)| -| 16. |[What is Event loop in Node.js? How does it work?](#q-what-is-event-loop-in-nodejs-how-does-it-work)| -| 17. |[What is REPL? What purpose it is used for?](#q-what-is-repl-what-purpose-it-is-used-for)| -| 18. |[What is the difference between Asynchronous and Non-blocking?](#q-what-is-the-difference-between-asynchronous-and-non-blocking)| -| 19. |[How to debug an application in Node.js?](#q-how-to-debug-an-application-in-nodejs)| -| 20. |[What are some of the most popular packages of Node.js?](#q-what-are-some-of-the-most-popular-packages-of-nodejs)| -| 21. |[What is EventEmitter in Node.js?](#q-what-is-eventemitter-in-nodejs)| -| 22. |[How many types of streams are present in node.js?](#q-how-many-types-of-streams-are-present-in-nodejs)| -| 23. |[What is crypto in Node.js? How do you cipher the secure information in Node.js?](#q-what-is-crypto-in-nodejs-how-do-you-cipher-the-secure-information-in-nodejs)| -| 24. |[What is the use of DNS module in Node.js?](#q-what-is-the-use-of-dns-module-in-nodejs)| -| 25. |[What are the security mechanisms available in Node.js?](#q-what-are-the-security-mechanisms-available-in-nodejs)| -| 26. |[Name the types of API functions in Node.js.](#q-name-the-types-of-api-functions-in-nodejs) -| 27. |[How does Node.js handle child threads?](#q-how-does-nodejs-handle-child-threads)| -| 28. |[What is the preferred method of resolving unhandled exceptions in Node.js?](#q-what-is-the-preferred-method-of-resolving-unhandled-exceptions-in-nodejs)| -| 29. |[How does Node.js support multi-processor platforms, and does it fully utilize all processor resources?](#q-how-does-nodejs-support-multi-processor-platforms-and-does-it-fully-utilize-all-processor-resources)| -| 30. |[What is typically the first argument passed to a Node.js callback handler?](#q-what-is-typically-the-first-argument-passed-to-a-nodejs-callback-handler)| -| 31. |[How Node.js read the content of a file?](#q-how-nodejs-read-the-content-of-a-file)| -| 32. |[What is JIT and how is it related to Node.js?](#q-what-is-jit-and-how-is-it-related-to-nodejs)| -| 33. |[What is difference between put and patch?](#q-what-is-difference-between-put-and-patch)| -| 34. |[List types of Http requests supported by Node.js.](#q-list-types-of-http-requests-supported-by-nodejs) -| 35. |[Why to use Express.js?](#q-why-to-use-expressjs)| -| 36. |[Write the steps for setting up an Express JS application.](#q-write-the-steps-for-setting-up-an-express-js-application) -| 37. |[Since node is a single threaded process, how to make use of all CPUs?](#q-since-node-is-a-single-threaded-process-how-to-make-use-of-all-cpus)| -| 38. |[What does emitter do and what is dispatcher?](#q-what-does-emitter-do-and-what-is-dispatcher)| -| 39. |[How to kill child processes that spawn their own child processes in Node.js?](#q-how-to-kill-child-processes-that-spawn-their-own-child-processes-in-nodejs)| -| 40. |[What do you understand by Reactor Pattern in Node.js?](#q-what-do-you-understand-by-reactor-pattern-in-nodejs)| -| 41. |[What are the key features of Node.js?](#q-what-are-the-key-features-of-nodejs)| -| 42. |[What are globals in Node.js?](#q-what-are-globals-in-nodejs)| -| 43. |[What is chaining process in Node.js?](#q-what-is-chaining-process-in-nodejs)| -| 44. |[What is a control flow function? what are the steps does it execute?](#q-what-is-a-control-flow-function-what-are-the-steps-does-it-execute)| -| 45. |[What is npm in Node.js?](#q-what-is-npm-in-nodejs)| -| 46. |[When to use Node.js and when not to use it?](#q-when-to-use-nodejs-and-when-not-to-use-it)| -| 47. |[Explain how does Node.js work?](#q-explain-how-does-nodejs-work)| -| 48. |[Is Node.js entirely based on a single-thread?](#q-is-nodejs-entirely-based-on-a-single-thread)| -| 49. |[How to make post request in Node.js?](#q-how-to-make-post-request-in-nodejs)| -| 50. |[Can you create http server in Node.js, explain the code used for it?](#q-can-you-create-http-server-in-nodejs-explain-the-code-used-for-it)| -| 51. |[How to load html in Node.js?](#q-how-to-load-html-in-nodejs)| -| 52. |[How can you listen on port 80 with Node?](#q-how-can-you-listen-on-port-80-with-node)| -| 53. |[What is the difference between operational and programmer errors?](#q-what-is-the-difference-between-operational-and-programmer-errors)| -| 54. |[Why npm shrinkwrap is useful?](#q-why-npm-shrinkwrap-is-useful)| -| 55. |[What is your favourite HTTP framework and why?](#q-what-is-your-favourite-http-framework-and-why)| -| 56. |[What are the Challenges with Node.js?](#q-what-are-the-challenges-with-nodejs)| -| 57. |[What is the difference between Node.js vs Ajax?](#q-what-is-the-difference-between-nodejs-vs-ajax)| -| 58. |[How Node.js overcomes the problem of blocking of I/O operations?](#q-how-nodejs-overcomes-the-problem-of-blocking-of-i-o-operations)| -| 59. |[Mention the steps by which you can async in Node.js?](#q-mention-the-steps-by-which-you-can-async-in-nodejs)| -| 60. |[What are the timing features of Node.js?](#q-what-are-the-timing-features-of-nodejs)| -| 61. |[What is LTS releases of Node.js why should you care?](#q-what-is-lts-releases-of-nodejs-why-should-you-care)| -| 62. |[Why should you separate Express 'app' and 'server'?](#q-why-should-you-separate-express-app-and-server)| -| 63. |[What is the difference between process.nextTick() and setImmediate()?](#q-what-is-the-difference-between-processnexttick-and-setimmediate)| -| 64. |[What is difference between JavaScript and Node.js?](#q-what-is-difference-between-javascript-and-nodejs)| -| 65. |[What are the difference between Events and Callbacks?](#q-what-are-the-difference-between-events-and-callbacks)| -| 66. |[Explain RESTful Web Services in Node.js?](#q-explain-restful-web-services-in-nodejs)| -| 67. |[How to handle file upload in Node js?](#q-how-to-handle-file-upload-in-node-js)| -| 68. |[Explain the terms body-parser, cookie-parser, debug, jade, morgan, nodemon, pm2, serve-favicon, cors in Express JS?](#q-explain-the-terms-body-parser-cookie-parser-debug-jade-morgan-nodemon-pm2-serve-favicon-cors-in-express-js)| -| 69. |[How does routing work in Node.js](#q-how-does-routing-work-in-node-js)| -| 70. |[How Node prevents blocking code?](#q-how-node-prevents-blocking-code)| -| 71. |[What is difference between promise and async await in node js?](#q-what-is-difference-between-promise-and-async-await-in-node-js)| -| 72. |[How to use JSON Web Token (JWT) for authentication in node js?](#q-how-to-use-json-web-token-jwt-for-authentication-in-node-js)| -| 73. |[How to build a microservices architecture with node js?](#q-how-to-build-a-microservices-architecture-with-node-js)| -| 74. |[How to use Q promise in node js?](#q-how-to-use-q-promise-in-node-js)| -| 75. |[How to use locale (i18n) in node js?](#q-how-to-use-locale-i18n-in-node-js)| -| 76. |[How to Implement Memcached in Nodejs?](#q-how-to-implement-memcached-in-nodejs)| -| 77. |[Explain Error Handling approaches in Nodejs?](#q-explain-error-handling-approaches-in-nodejs)| -| 78. |[How to generate and verify checksum of the given string in Nodejs](#q-how-to-generate-and-verify-checksum-of-the-given-string-in-nodejs)| -| 79. |[What is Callback function in node.js?](#q-what-is-callback-function-in-nodejs)| -| 80. |[What is asynchronous programming in node.js?](#q-what-is-asynchronous-programming-in-nodejs)| -| 81. |[How to implement asymmetric cryptography when signing and verify JSON Web Token (JWT) for authentication in node js?](#q-how-to-implement-asymmetric-cryptography-when-signing-and-verifying-json-web-token-jwt-for-authentication-in-node-js) | +## Table of Contents + +* [Introduction](#-1-introduction) +* [Node.js Setup](#-2-nodejs-setup) +* [Node.js Data Types](#-3-nodejs-data-types) +* [Node.js Architecture](#-4-nodejs-architecture) +* [Node.js Events](#-5-nodejs-events) +* [Node.js File System](#-6-nodejs-file-system) +* [Node.js Streams](#-7-nodejs-streams) +* [Node.js Multithreading](#-8-nodejs-multithreading) +* [Node.js Web Module](#-9-nodejs-web-module) +* [Node.js Middleware](#-10-nodejs-middleware) +* [Node.js RESTFul API](#-11-nodejs-restful-api) +* [Node.js Routing](#-12-nodejs-routing) +* [Node.js Caching](#-13-nodejs-caching) +* [Node.js Error Handling](#-14-nodejs-error-handling) +* [Node.js Logging](#-15-nodejs-logging) +* [Node.js Internationalization](#-16-nodejs-internationalization) +* [Node.js Testing](#-17-nodejs-testing) +* [Node.js Miscellaneous](#-18-nodejs-miscellaneous)
+## # 1. INTRODUCTION + +
-## Q. ***What is Node.js?*** +## Q. What is Node.js? Node.js is an open-source server side runtime environment built on Chrome\'s V8 JavaScript engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.
- ↥ back to top + ↥ back to top
-## Q. ***What are the benefits of using Node.js?*** - -From a web server development perspective Node has a number of benefits: +## Q. What is Node.js Process Model? - * Great performance! Node was designed to optimize throughput and scalability in web applications and is a good solution for many common web-development problems (e.g. real-time web applications). +Node.js runs in a single process and the application code runs in a single thread and thereby needs less resources than other platforms. - * Code is written in "plain old JavaScript", which means that less time is spent dealing with "context shift" between languages when you're writing both client-side and server-side code. +All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed asynchronously for a particular request. So, this single thread doesn\'t have to wait for the request to complete and is free to handle the next request. When asynchronous I/O work completes then it processes the request further and sends the response. - * JavaScript is a relatively new programming languages and benefits from improvements in language design when compared to other traditional web-server languages (e.g. Python, PHP, etc.) Many other new and pouplar languages compile/convert into JavaScript so you can use TypeScript, CoffeeScript, ClojureScript, Scala, LiveScript, etc. +
+ ↥ back to top +
- * The node package manager (NPM) provides access to hundres of thousands of resuable packages. It also has best-in-class dependency resolution and can also be used to automate most of the build toolchain. +## Q. What are the key features of Node.js? - * Node.js is portable. It is available on Microsoft Windows, macOS, Linux, Solaris, FreeBSD, OpenBSD, WebOS, and NonStop OS. Furthermore, it is well-supported by many web hosting providers, that often provide specific infrastrucutre and documentation for hosting - Node sites. +* **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. - * It has a very active third party ecosystem and developer community, with lots of people who are willing to help. - +* **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. +* **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. -
- ↥ back to top -
+* **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. -## Q. ***What is Node.js Process Model?*** +* **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. -Node.js runs in a single process and the application code runs in a single thread and thereby needs less resources than other platforms. All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed asynchronously for a particular request. So, this single thread doesn't have to wait for the request to complete and is free to handle the next request. When asynchronous I/O work completes then it processes the request further and sends the response. +* **No Buffering** – Node.js applications never buffer any data. They simply output the data in chunks.
- ↥ back to top + ↥ back to top
-## Q. ***What are the data types in Node.js?*** +## Q. How does Node.js work? -Just like JS, there are two categories of data types in Node: Primitives and Objects. +A 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. -*Primitives* +Node.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. -* String -* Number -* Bigint -* Boolean -* Undefined -* Null -* Symbol +While 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. -*Objects* +
+ ↥ back to top +
-* Function +## Q. What is difference between process and threads in Node.js? -* Array +**1. Process:** -* `Buffer`: Node.js includes an additional data type called Buffer (not available in browser\'s JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network. `Buffer` is a class. +Processes 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. +The process can have the following states new, ready, running, waiting, terminated, and suspended. -* other regular objects +**2. Thread:** +Thread 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. +The thread takes less time to terminate as compared to the process but unlike the process, threads do not isolate.
- ↥ back to top + ↥ back to top
-## Q. ***How to create a simple server in Node.js that returns Hello World?*** +## # 2. NODE.JS SETUP + +
+ +## Q. How to create a simple server in Node.js that returns Hello World? **Step 01**: Create a project directory -```bash +```js mkdir myapp cd myapp ``` **Step 02**: Initialize project and link it to npm -```bash +```js npm init ``` This 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. You can enter your way through all of them EXCEPT this one: -```bash +```js entry point: (index.js) ``` Rename this to: -```bash +```js app.js ``` **Step 03**: Install Express in the myapp directory -```bash +```js npm install express --save ``` **Step 04**: app.js ```js -var express = require('express'); -var app = express(); +/** + * Express.js + */ +const express = require('express'); +const app = express(); + app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(3000, function () { - console.log('Example app listening on port 3000!'); + console.log('App listening on port 3000!'); }); ``` @@ -221,592 +172,638 @@ app.listen(3000, function () { node app.js ``` +**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/hello-world-in-nodejs-ue3cs3)** +
- ↥ back to top + ↥ back to top
-## Q. ***Explain the concept of URL module in Node.js?*** +## Q. Explain the concept of URL module in Node.js? -The URL module in Node.js splits up a web address into readable parts. Use ```require()``` to include the module: +The 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. -```javascript -var url = require('url'); -``` -Then parse an address with the ```url.parse()``` method, and it will return a URL object with each part of the address as properties. +**Example:** -```javascript -var url = require('url'); -var adr = 'http://localhost:8080/default.htm?year=2021&month=september'; -var q = url.parse(adr, true); +```js +/** + * URL Module in Node.js + */ +const url = require('url'); +const adr = 'http://localhost:8080/default.htm?year=2022&month=september'; +const q = url.parse(adr, true); -console.log(q.host); //returns 'localhost:8080' -console.log(q.pathname); //returns '/default.htm' -console.log(q.search); //returns '?year=2021&month=september' +console.log(q.host); // localhost:8080 +console.log(q.pathname); // "/default.htm" +console.log(q.search); // "?year=2022&month=september" -var qdata = q.query; //returns an object: { year: 2021, month: 'september' } -console.log(qdata.month); //returns 'september' +const qdata = q.query; // { year: 2022, month: 'september' } +console.log(qdata.month); // "september" ```
- ↥ back to top + ↥ back to top
+## # 3. NODE.JS DATA TYPES -## Q. ***How to make an HTTP POST request using Node.js?*** +
-```js -const https = require('https') +## Q. What are the data types in Node.js? +Just like JS, there are two categories of data types in Node: Primitives and Objects. -const obj = { - "userId":1, - "id":1, - "title":"whatever", - "completed":false -} +**1. Primitives:** -const data = JSON.stringify(obj) +* String +* Number +* BigInt +* Boolean +* Undefined +* Null +* Symbol -const options = { - hostname: 'jsonplaceholder.typicode.com', - port: 443, - path: '/todos', - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': data.length - } -} +**2. Objects:** -const req = https.request(options, res => { - console.log(`statusCode: ${res.statusCode}`) +* Function +* Array +* Buffer - res.on('data', d => { - process.stdout.write(d) - }) -}) +
+ ↥ back to top +
-req.on('error', error => { - console.error(error) -}) +## Q. Explain String data type in Node.js? -req.write(data) -req.end() -``` +Strings in Node.js are sequences of unicode characters. Strings can be wrapped in a single or double quotation marks. +Javascript provide many functions to operate on string, like indexOf(), split(), substr(), length. -
- ↥ back to top -
+**String functions:** -## Q. ***How to execute an external program from within Node.js?*** +|Function | Description | +|-----------|---------------------------| +|charAt() |It is useful to find a specific character present in a string.| +|concat() |It is useful to concat more than one string.| +|indexOf() |It is useful to get the index of a specified character or a part of the string.| +|match() |It is useful to match multiple strings.| +|split() |It is useful to split the string and return an array of string.| +|join() |It is useful to join the array of strings and those are separated by comma (,) operator.| -const { exec } = require('child_process'); +**Example:** -exec('"/path/to/test file/test.sh" arg1 arg2'); +```js +/** + * String Data Type + */ +const str1 = "Hello"; +const str2 = 'World'; -exec('echo "The \\$HOME variable is $HOME"'); +console.log("Concat Using (+) :" , (str1 + ' ' + str2)); +console.log("Concat Using Function :" , (str1.concat(str2))); +```
- ↥ back to top + ↥ back to top
-## Q. ***What does the runtime environment mean in Node.js?*** +## Q. Explain Number data type in Node.js? -The Node.js runtime is the software stack responsible for installing your web service\'s code and its dependencies and running your service. +The 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`. -The Node.js runtime for App Engine in the standard environment is declared in the `app.yaml` file: +**Example:** ```js -runtime: nodejs10 -``` +/** + * Number Data Type + */ +// Example 01: +const num1 = 10; +const num2 = 20; -The runtime environment is literally just the environment your application is running in. This can be used to describe both the hardware and the software that is running your application. How much RAM, what version of node, what operating system, how much CPU cores, can all be referenced when talking about a runtime environment. +console.log(`sum: ${num1 + num2}`); +// Example 02: +console.log(parseInt("32")); // 32 +console.log(parseFloat("8.24")); // 8.24 +console.log(parseInt("234.12345")); // 234 +console.log(parseFloat("10")); // 10 + +// Example 03: +console.log(isFinite(10/5)); // true +console.log(isFinite(10/0)); // false + +// Example 04: +console.log(5 / 0); // Infinity +console.log(-5 / 0); // -Infinity +```
- ↥ back to top + ↥ back to top
-## Q. ***Explain usage of NODE_ENV?*** +## Q. Explain BigInt data type in Node.js? -NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. +A 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. -For example, when we work on a project and there are production and development environments. We don't need to use caching in the development env. So we set - ```bash - $ NODE_ENV=development - ``` +**Example:** -and use the code below ```js -if (process.env.NODE_ENV === 'development') - useCaching = false; -``` -Upon that, if the project runs on production it will use caching. +/** + * BigInt Data Type + */ +const maxSafeInteger = 99n; // This is a BigInt +const num2 = BigInt('99'); // This is equivalent +const num3 = BigInt(99); // Also works +typeof 1n === 'bigint' // true +typeof BigInt('1') === 'bigint' // true +```
- ↥ back to top + ↥ back to top
-## Q. ***How do Node.js works?*** - -

- Node Architecture -

+## Q. Explain Boolean data type in Node.js? -Node is completely event-driven. Basically the server consists of one thread processing one event after another. +Boolean 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. -A new request coming in is one kind of event. The server starts processing it and when there is a blocking IO operation, it does not wait until it completes and instead registers a callback function. The server then immediately starts to process another event (maybe another request). When the IO operation is finished, that is another kind of event, and the server will process it (i.e. continue working on the request) by executing the callback as soon as it has time. +The 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. -So the server never needs to create additional threads or switch between threads, which means it has very little overhead. If you want to make full use of multiple hardware cores, you just start multiple instances of node.js +**Example:** -Node JS Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model. Node JS Processing model mainly based on Javascript Event based model with Javascript callback mechanism. - -**Single Threaded Event Loop Model Processing Steps:** +```js +/** + * Boolean Data Type + */ +// Example 01: +const isValid = true; +console.log(isValid); // true -* Clients Send request to Web Server. -* Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests. -* Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”. -* Node JS Web Server internally has a Component, known as “Event Loop”. Why it got this name is that it uses indefinite loop to receive requests and process them. -* Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model. -* Event Loop checks any Client Request is placed in Event Queue. If no, then wait for incoming requests for indefinitely. -* If yes, then pick up one Client Request from Event Queue - * Starts process that Client Request - * If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client. - * If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach - * Checks Threads availability from Internal Thread Pool - * Picks up one Thread and assign this Client Request to that thread. - * That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop - * Event Loop in turn, sends that Response to the respective Client. +// Example 02: +console.log(true && true); // true +console.log(true && false); // false +console.log(true || false); // true +console.log(false || false); // false +console.log(!true); // false +console.log(!false); // true +```
- ↥ back to top + ↥ back to top
-## Q. ***What is the difference between Node.js, AJAX, and JQuery?*** +## Q. Explain `Undefined` and `Null` data type in Node.js? + +In 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**. -Node.js is a javascript runtime that makes it possible for us to write back-end of applications. +**Example:** -Asynchronous JavaScript and XML(AJAX) refers to group of technologies that we use to send requests to web servers and retrieve data from them without reloading the page. +```js +/** + * NULL and UNDEFINED Data Type + */ +let x; +console.log(x); // undefined -Jquery is a simple javascript library that helps us with front-end development. +let y = null; +console.log(y); // null +```
- ↥ back to top + ↥ back to top
-## Q. ***What are the core modules of Node.js?*** +## Q. Explain Symbol data type in Node.js? +Symbol 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. -They are defined within the Node.js source and are located in the lib/ folder, and Node.js has several modules compiled into the binary. +**Example:** -Core modules are always preferentially loaded if their identifier is passed to ```require()```. For instance, ```require('http')``` will always return the built in HTTP module, even if there is a file by that name. +```js +/** + * Symbol Data Type + */ +const NAME = Symbol() +const person = { + [NAME]: 'Ritika Bhavsar' +} -Core modules can also be identified using the ```node:``` prefix, in which case it bypasses the require cache. For instance, ```require('node:http')``` will always return the built in HTTP module, even if there is ```require.cache``` entry by that name. +person[NAME] // 'Ritika Bhavsar' +```
- ↥ back to top + ↥ back to top
-## Q. ***What is callback function in Node.js?*** +## Q. Explain function in Node.js? + +Functions 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. -In node.js, we basically use callbacks for handling asynchronous operations like — making any I/O request, database operations or calling an API to fetch some data. Callback allows our code to not get blocked when a process is taking a long time. +**Example:** -```javascript -function myNew(next){ - console.log("Im the one who initates callback"); - next("nope", "success"); +```js +/** + * Function in Node.js + */ +function Messsage(name) { + console.log("Hello "+name); } -myNew(function(err, res){ - console.log("I got back from callback",err, res); -}); +Messsage("World"); // Hello World ```
- ↥ back to top + ↥ back to top
-## Q. ***How assert works in Node.js?*** +## Q. Explain Buffer data type in Node.js? -The assert module provides a way of testing expressions. If the expression evaluates to 0, or false, an assertion failure is being caused, and the program is terminated. +Node.js includes an additional data type called Buffer ( not available in browser\'s JavaScript ). Buffer is mainly used to store **binary data**, while reading from a file or receiving packets over the network. -This module was built to be used internally by Node.js. +**Example:** -``` -// Sample usage +```js +/** + * Buffer Data Type + */ +let b = new Buffer(10000); +let str = "----------"; -const assert = require('assert'); -assert(50 > 70, "50 is less than 70."); +b.write(str); +console.log( str.length ); // 10 +console.log( b.length ); // 10000 ``` +*Note: Buffer() is deprecated due to security and usability issues.* +
- ↥ back to top + ↥ back to top
-## Q. ***What is an error-first callback?*** +## # 4. NODE.JS ARCHITECTURE -The pattern used across all the asynchronous methods in Node.js is called *Error-first Callback*. Here is an example: +
-```javascript -fs.readFile( "file.json", function ( err, data ) { - if ( err ) { - console.error( err ); - } - console.log( data ); -}); -``` +## Q. How does Node.js works? -Any 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. +Node.js is completely event-driven. Basically the server consists of one thread processing one event after another. -In 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. +A new request coming in is one kind of event. The server starts processing it and when there is a blocking IO operation, it does not wait until it completes and instead registers a callback function. The server then immediately starts to process another event ( maybe another request ). When the IO operation is finished, that is another kind of event, and the server will process it ( i.e. continue working on the request ) by executing the callback as soon as it has time. + +Node.js Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model. Node.js Processing model mainly based on Javascript Event based model with Javascript callback mechanism. + +

+ Node Architecture +

+ +**Single Threaded Event Loop Model Processing Steps:** + +* Clients Send request to Web Server. +* Node.js Web Server internally maintains a Limited Thread pool to provide services to the Client Requests. +* Node.js Web Server receives those requests and places them into a Queue. It is known as **Event Queue**. +* Node.js Web Server internally has a Component, known as **Event Loop**. Why it got this name is that it uses indefinite loop to receive requests and process them. +* Event Loop uses Single Thread only. It is main heart of Node.js Platform Processing Model. +* Event Loop checks any Client Request is placed in Event Queue. If no, then wait for incoming requests for indefinitely. +* If yes, then pick up one Client Request from Event Queue + * Starts process that Client Request + * If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client. + * If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach + * Checks Threads availability from Internal Thread Pool + * Picks up one Thread and assign this Client Request to that thread. + * That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop + * Event Loop in turn, sends that Response to the respective Client.
- ↥ back to top + ↥ back to top
-## Q. ***What is callback hell in Node.js?*** +## Q. What are the core modules of Node.js? -`Callback hell` is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the other. +Node.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. -An asynchronous function is one where some external activity must complete before a result can be processed; it is “asynchronous” in the sense that there is an unpredictable amount of time before a result becomes available. Such functions require a callback function to handle errors and process the result. +**Syntax:** -```javascript -getData(function(a){ - getMoreData(a, function(b){ - getMoreData(b, function(c){ - getMoreData(c, function(d){ - getMoreData(d, function(e){ - ... - }); - }); - }); - }); -}); +```js +const module = require('module_name'); ``` -**Techniques for avoiding callback hell** - -1. Using Async.js -1. Using Promises -1. Using Async-Await +**Example:** -* **Managing callbacks using Async.js** +```js +const http = require('http'); -`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. +http.createServer(function (req, res) { + res.writeHead(200, {'Content-Type': 'text/html'}); + res.write('Welcome to Node.js!'); + res.end(); +}).listen(3000); +``` + +The following table lists some of the important core modules in Node.js. + +|Name |Description | +|-------------|--------------------------------------------------------| +|Assert |It is used by Node.js for testing itself. It can be accessed with require('assert').| +|Buffer |It is used to perform operations on raw bytes of data which reside in memory. It can be accessed with require('buffer')| +|Child Process|It is used by node.js for managing child processes. It can be accessed with require('child_process').| +|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').| +|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'). | +|Crypto |It is used to support cryptography for encryption and decryption. It can be accessed with require('crypto').| +|HTTP |It includes classes, methods and events to create Node.js http server.| +|URL |It includes methods for URL resolution and parsing.| +|Query String |It includes methods to deal with query string.| +|Path |It includes methods to deal with file paths.| +|File System |It includes classes, methods, and events to work with file I/O.| +|Util |It includes utility functions useful for programmers.| +|Zlib |It is used to compress and decompress data. It can be accessed with require('zlib').| -Async provides lots of powerful utilities to work with asynchronous processes under different scenarios. +
+ ↥ back to top +
-```bash -npm install --save async -``` +## Q. What do you understand by Reactor Pattern in Node.js? -* **ASYNC WATERFALL** - -```javascript -var async = require('async'); -async.waterfall([ - function(callback) { - //doSomething - callback(null, paramx); //paramx will be availaible as the first parameter to the next function - /** - The 1st parameter passed in callback. - @null or @undefined or @false control moves to the next function - in the array - if @true or @string the control is immedeatly moved - to the final callback fucntion - rest of the functions in the array - would not be executed - */ - }, - function(arg1, callback) { - //doSomething else - // arg1 now equals paramx - callback(null, result); - }, - function(arg1, callback) { - //do More - // arg1 now equals result - callback(null, 'done'); - }, - function(arg1, callback) { - //even more - // arg1 now equals 'done' - callback(null, 'done'); - } -], function (err, result) { - //final callback function - //finally do something when all function are done. - // result now equals 'done' -}); -``` +**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. -* **ASYNC SERIES** - -```javascript -var async = require('async'); -async.series([ - function(callback){ - // do some stuff ... - callback(null, 'one'); - /** - The 1st parameter passed in callback. - @null or @undefined or @false control moves to the next function - in the array - if @true or @string the control is immedeatly moved - to the final callback fucntion with the value of err same as - passed over here and - rest of the functions in the array - would not be executed - */ - }, - function(callback){ - // do some more stuff ... - callback(null, 'two'); - } -], -// optional callback -function(err, results){ - // results is now equal to ['one', 'two'] -}); -``` +**There are two ways in which I/O operations are performed:** -* **Managing callbacks hell using promises** +**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". -Promises 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. The `.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. +**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". -```javascript -var outputPromise = getInputPromise().then(function (input) { - //handle success -}, function (error) { - //handle error -}); -``` +

+ Reactor Pattern +

-* **Using Async Await** +**Reactor Pattern comprises of:** -Async 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. +**1. Resources:** They are shared by multiple applications for I/O operations, generally slower in executions. -```javascript -const getrandomnumber = function(){ - return new Promise((resolve, reject)=>{ - setTimeout(() => { - resolve(Math.floor(Math.random() * 20)); - }, 1000); - }); -} +**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. -const addRandomNumber = async function(){ - const sum = await getrandomnumber() + await getrandomnumber(); - console.log(sum); -} +**3. Event Loop and Event Queue:** Event Queue queues up the new events that occurred along with its event-handler, pair. -addRandomNumber(); -``` +**4. Request Handler/Application:** This is, generally, the application that provides the handler to be executed for registered events on resources.
- ↥ back to top + ↥ back to top
-## Q. ***What are Promises in Node.js?*** +## Q. What are the global objects of Node.js? -It allows to associate handlers to an asynchronous action\'s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise for the value at some point in the future. - -Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete). +Node.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. -The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states: +These objects are modules, functions, strings and object itself as explained below. -* pending - The initial state of a promise. -* fulfilled - The state of a promise representing a successful operation. -* rejected - The state of a promise representing a failed operation. -Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again). +**1. global:** -**Creating a Promise** +It is a global namespace. Defining a variable within this namespace makes it globally accessible. -```javascript -var myPromise = new Promise(function(resolve, reject){ - .... -}) +```js +var myvar; ``` -
- ↥ back to top -
+**2. process:** -## Q. ***What tools can be used to assure consistent style?*** +It 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. -* ESLint -* Standard +**3. console:** -
- ↥ back to top -
+It is an inbuilt global object used to print to stdout and stderr. + +```js +console.log("Hello World"); // Hello World +``` -## Q. ***When should you npm and when yarn?*** +**4. setTimeout(), clearTimeout(), setInterval(), clearInterval():** -* **npm** +The built-in timer functions are globals -It is the default method for managing packages in the Node.js runtime environment. It relies upon a command line client and a database made up of public and premium packages known as the the npm registry. Users can access the registry via the client and browse the many packages available through the npm website. Both npm and its registry are managed by npm, Inc. +```js +function printHello() { + console.log( "Hello, World!"); +} -```bash -node -v -npm -v +// Now call above function after 2 seconds +var timeoutObj = setTimeout(printHello, 2000); ``` -* **Yarn** +**5. __dirname:** -Yarn was developed by Facebook in attempt to resolve some of npm’s shortcomings. Yarn isn’t technically a replacement for npm since it relies on modules from the npm registry. Think of Yarn as a new installer that still relies upon the same npm structure. The registry itself hasn’t changed, but the installation method is different. Since Yarn gives you access to the same packages as npm, moving from npm to Yarn doesn’t require you to make any changes to your workflow. +It is a string. It specifies the name of the directory that currently contains the code. -```bash -npm install yarn --global +```js +console.log(__dirname); ``` -**Comparing Yarn vs npm** +**6. __filename:** -* Fast: Yarn caches every package it downloads so it never needs to again. It also parallelizes operations to maximize resource utilization so install times are faster than ever. -* Reliable: Using a detailed, but concise, lockfile format, and a deterministic algorithm for installs, Yarn is able to guarantee that an install that worked on one system will work exactly the same way on any other system. -* Secure: Yarn uses checksums to verify the integrity of every installed package before its code is executed. -* Offline Mode: If you've installed a package before, you can install it again without any internet connection. -* Deterministic: The same dependencies will be installed the same exact way across every machine regardless of install order. -* Network Performance: Yarn efficiently queues up requests and avoids request waterfalls in order to maximize network utilization. -* Multiple Registries: Install any package from either npm or Bower and keep your package workflow the same. -* Network Resilience: A single request failing won't cause an install to fail. Requests are retried upon failure. -* Flat Mode: Resolve mismatching versions of dependencies to a single version to avoid creating duplicates. +It 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. + +```js +console.log(__filename); +```
- ↥ back to top + ↥ back to top
-## Q. ***What is a stub?*** - -Stubbing and verification for node.js tests. Enables you to validate and override behaviour of nested pieces of code such as methods, require() and npm modules or even instances of classes. This library is inspired on node-gently, MockJS and mock-require. +## Q. What is chrome v8 engine? -**Features of Stub:** +V8 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. -* Produces simple, lightweight Objects capable of extending down their tree -* Compatible with Nodejs -* Easily extendable directly or through an ExtensionManager -* Comes with predefined, usable extensions +V8 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. -Stubs are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made during test cases. Also, you can assert on with what these stubs were called. +V8 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. -A use-case can be a file read, when you do not want to read an actual file: +
+ ↥ back to top +
-```javascript -var fs = require('fs'); +## Q. Why is LIBUV needed in Node JS? -var readFileStub = sinon.stub(fs, 'readFile', function (path, cb) { - return cb(null, 'filecontent'); -}); +**libuv** is a C library originally written for Node.js to abstract non-blocking I/O operations. It provides the following features: -expect(readFileStub).to.be.called; -readFileStub.restore(); -``` +* 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. +* It facilitates an event-driven approach wherein I/O and other activities are performed using callback-based notifications. +* It provides mechanisms to handle file system, DNS, network, child processes, pipes, signal handling, polling and streaming +* It also includes a thread pool for offloading work for some things that can\'t be done asynchronously at the operating system level.
- ↥ back to top + ↥ back to top
-## Q. ***What is a test pyramid? How can you implement it when talking about HTTP APIs?*** +## Q. How V8 compiles JavaScript code? -The "Test Pyramid" is a metaphor that tells us to group software tests into buckets of different granularity. It also gives an idea of how many tests we should have in each of these groups. It shows which kinds of tests you should be looking for in the different levels of the pyramid and gives practical examples on how these can be implemented. - -

- Test Pyramid -

+Compilation is the process of converting human-readable code to machine code. There are two ways to compile the code -Mike Cohn\'s original test pyramid consists of three layers that your test suite should consist of (bottom to top): +* **Using an Interpreter**: The interpreter scans the code line by line and converts it into byte code. +* **Using a Compiler**: The Compiler scans the entire document and compiles it into highly optimized byte code. -1. Unit Tests -1. Service Tests -1. User Interface Tests +The 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.
- ↥ back to top + ↥ back to top
-## Q. ***How can you secure your HTTP cookies against XSS attacks?*** +## # 5. NODE.JS EVENTS -**1.** When the web server sets cookies, it can provide some additional attributes to make sure the cookies won\'t be accessible by using malicious JavaScript. One such attribute is HttpOnly. +
-```javascript -Set-Cookie: [name]=[value]; HttpOnly -``` +## Q. What is EventEmitter in Node.js? -HttpOnly makes sure the cookies will be submitted only to the domain they originated from. +The 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. -**2.** The "Secure" attribute can make sure the cookies are sent over secured channel only. +EventEmitter 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: -```javascript -Set-Cookie: [name]=[value]; Secure -``` +* Emitting name events. +* Registering and unregistering listener functions. -**3.** The web server can use X-XSS-Protection response header to make sure pages do not load when they detect reflected cross-site scripting (XSS) attacks. +**Example:** -```javascript -X-XSS-Protection: 1; mode=block -``` +```js +/** + * Callback Events with Parameters + */ +const events = require('events'); +const eventEmitter = new events.EventEmitter(); -**4.** The web server can use HTTP Content-Security-Policy response header to control what resources a user agent is allowed to load for a certain page. It can help to prevent various types of attacks like Cross Site Scripting (XSS) and data injection attacks. +function listener(code, msg) { + console.log(`status ${code} and ${msg}`); +} -```javascript -Content-Security-Policy: default-src 'self' *.http://sometrustedwebsite.com +eventEmitter.on('status', listener); // Register listener +eventEmitter.emit('status', 200, 'ok'); + +// Output +status 200 and ok ```
- ↥ back to top + ↥ back to top
-## Q. ***How can you make sure your dependencies are safe?*** +## Q. How does the EventEmitter works in Node.js? -The only option is to automate the update / security audit of your dependencies. For that there are free and paid options: +* Event Emitter emits the data in an event called message +* A Listened is registered on the event message +* when the message event emits some data, the listener will get the data -1. npm outdated -2. Trace by RisingStack -3. NSP -4. GreenKeeper -5. Snyk -6. npm audit -7. npm audit fix +

+ EventEmitter +

-
- ↥ back to top -
+**Building Blocks:** + +* **.emit()** - this method in event emitter is to emit an event in module +* **.on()** - this method is to listen to data on a registered event in node.js +* **.once()** - it listen to data on a registered event only once. +* **.addListener()** - it checks if the listener is registered for an event. +* **.removeListener()** - it removes the listener for an event. + +

+ Building Blocks +

+ +**Example 01:** + +```js +/** + * Callbacks Events + */ +const events = require('events'); +const eventEmitter = new events.EventEmitter(); + +function listenerOne() { + console.log('First Listener Executed'); +} + +function listenerTwo() { + console.log('Second Listener Executed'); +} -## Q. ***What is Event loop in Node.js? How does it work?*** +eventEmitter.on('listenerOne', listenerOne); // Register for listenerOne +eventEmitter.on('listenerOne', listenerTwo); // Register for listenerOne -The event loop is what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible. +// When the event "listenerOne" is emitted, both the above callbacks should be invoked. +eventEmitter.emit('listenerOne'); -Node.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. +// Output +First Listener Executed +Second Listener Executed +``` -**Event-Driven Programming** +**Example 02:** -In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected. +```js +/** + * Emit Events Once + */ +const events = require('events'); +const eventEmitter = new events.EventEmitter(); -Although events look quite similar to callbacks, the difference lies in the fact that callback 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 as follows +function listenerOnce() { + console.log('listenerOnce fired once'); +} -```javascript -// Import events module -var events = require('events'); +eventEmitter.once('listenerOne', listenerOnce); // Register listenerOnce +eventEmitter.emit('listenerOne'); -// Create an eventEmitter object -var eventEmitter = new events.EventEmitter(); +// Output +listenerOnce fired once ``` -*Example*: +
+ ↥ back to top +
+ +## Q. What are the EventEmitter methods available in Node.js? + +|EventEmitter Methods | Description | +|---------------------|---------------------| +|.addListener(event, listener) |Adds a listener to the end of the listeners array for the specified event.| +|.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()| +|.once(event, listener)|This listener is invoked only the next time the event is fired, after which it is removed.| +|.removeListener(event, listener)|Removes a listener from the listener array for the specified event.| +|.removeAllListeners([event])|Removes all listeners, or those of the specified event.| +|.setMaxListeners(n) |By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.| +|.getMaxListeners() |Returns the current maximum listener value for the emitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.| +|.listeners(event) |Returns a copy of the array of listeners for the specified event.| +|.emit(event[, arg1][, arg2][, ...]) |Raise the specified events with the supplied arguments.| +|.listenerCount(type) |Returns the number of listeners listening to the type of event.| + +
+ ↥ back to top +
+ +## Q. How the Event Loop Works in Node.js? + +The **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. + +Node.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. + +**Features of Event Loop:** + +* Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks. +* The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task. +* The event loop allows us to use callbacks and promises. +* The event loop executes the tasks starting from the oldest first. + +

+ Event Loop +

-```javascript -// Import events module -var events = require('events'); +**Example:** -// Create an eventEmitter object -var eventEmitter = new events.EventEmitter(); +```js +/** + * Event loop in Node.js + */ +const events = require('events'); +const eventEmitter = new events.EventEmitter(); // Create an event handler as follows -var connectHandler = function connected() { +const connectHandler = function connected() { console.log('connection succesful.'); - - // Fire the data_received event eventEmitter.emit('data_received'); } @@ -820,572 +817,610 @@ eventEmitter.on('data_received', function() { // Fire the connection event eventEmitter.emit('connection'); - console.log("Program Ended."); + +// Output +Connection succesful. +Data received succesfully. +Program Ended. ```
- ↥ back to top + ↥ back to top
-## Q. ***If Node.js is single threaded then how it handles concurrency?*** +## Q. How are event listeners created in Node.JS? -*ToDo* +An 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. + +The 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. + +```js +emitter.setMaxlisteners(12); +``` + +As 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.
- ↥ back to top + ↥ back to top
-## Q. ***What is REPL? What purpose it is used for?*** +## Q. What is the difference between process.nextTick() and setImmediate()? -REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell (Unix/Linux) and command prompt. Node comes with the REPL environment when it is installed. System interacts with the user through outputs of commands/expressions used. It is useful in writing and debugging the codes. The work of REPL can be understood from its full form: +**1. process.nextTick():** -* **Read**: It reads the inputs from users and parses it into JavaScript data structure. It is then stored to memory. -* **Eval**: The parsed JavaScript data structure is evaluated for the results. -* **Print**: The result is printed after the evaluation. -* **Loop**: Loops the input command. To come out of NODE REPL, press ctrl+c twice +The 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. -Simple Expression +**2. setImmediate():** + +The 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. + +**Example:** ```js -$ node -> 10 + 20 -30 -> 10 + ( 20 * 30 ) - 40 -570 -> -``` +/** + * setImmediate() and process.nextTick() + */ +setImmediate(() => { + console.log("1st Immediate"); +}); -
- ↥ back to top -
+setImmediate(() => { + console.log("2nd Immediate"); +}); + +process.nextTick(() => { + console.log("1st Process"); +}); + +process.nextTick(() => { + console.log("2nd Process"); +}); -## Q. ***What is asynchronous programming in Node.js?*** +// First event queue ends here +console.log("Program Started"); -Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. When the work is complete, it notifies the main thread (as well as whether the work was completed or failed). There are numerous benefits to using it, such as improved application performance and enhanced responsiveness. +// Output +Program Started +1st Process +2nd Process +1st Immediate +2nd Immediate +```
- ↥ back to top + ↥ back to top
-## Q. ***What is the difference between Asynchronous and Non-blocking?*** +## Q. What is callback function in Node.js? -**1. Asynchronous** +A 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. -The architecture of asynchronous explains that the message sent will not give the reply on immediate basis just like we send the mail but do not get the reply on an immediate basis. It does not have any dependency or order. Hence improving the system efficiency and performance. The server stores the information and when the action is done it will be notified. +Callback 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. -**2. Non-Blocking** +**Example:** -Nonblocking immediately responses with whatever data available. Moreover, it does not block any execution and keeps on running as per the requests. If an answer could not be retrieved then in those cases API returns immediately with an error. Nonblocking is mostly used with I/O(input/output). Node.js is itself based on nonblocking I/O model. There are few ways of communication that a nonblocking I/O has completed. The callback function is to be called when the operation is completed. Nonblocking call uses the help of javascript which provides a callback function. +```js +/** + * Callback Function + */ +function message(name, callback) { + console.log("Hi" + " " + name); + callback(); +} -* **Asynchronous VS Non-Blocking** +// Callback function +function callMe() { + console.log("I am callback function"); +} + +// Passing function as an argument +message("Node.JS", callMe); +``` + +**Output:** -1) Asynchronous does not respond immediately, While Nonblocking responds immediately if the data is available and if not that simply returns an error. -2) Asynchronous improves the efficiency by doing the task fast as the response might come later, meanwhile, can do complete other tasks. Nonblocking does not block any execution and if the data is available it retrieves the information quickly. -3) Asynchronous is the opposite of synchronous while nonblocking I/O is the opposite of blocking. They both are fairly similar but they are also different as asynchronous is used with a broader range of operations while nonblocking is mostly used with I/O. +```js +Hi Node.JS +I am callback function +```
- ↥ back to top + ↥ back to top
-## Q. ***How to debug an application in Node.js?*** +## Q. What are the difference between Events and Callbacks? -* **node-inspector** +**1. Events:** -```bash -npm install -g node-inspector -``` +Node.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. -Run +All 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 -```bash -node-debug app.js -``` +**Example:** -* **Debugging** - * Debugger - * Node Inspector - * Visual Studio Code - * Cloud9 - * Brackets +```js +/** + * Events Module + */ +const event = require('events'); +const eventEmitter = new event.EventEmitter(); + +// add listener function for Sum event +eventEmitter.on('Sum', function(num1, num2) { + console.log('Total: ' + (num1 + num2)); +}); -* **Profiling** +// call event +eventEmitter.emit('Sum', 10, 20); -```bash -1. node --prof ./app.js -2. node --prof-process ./the-generated-log-file +// Output +Total: 30 ``` -* **Heapdumps** - * node-heapdump with Chrome Developer Tools +**2. Callbacks:** -* **Tracing** - * Interactive Stack Traces with TraceGL +A 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. -* **Logging** -Libraries that output debugging information - * Caterpillar - * Tracer - * scribbles - -Libraries that enhance stack trace information -* Longjohn +**Example:** -
- ↥ back to top -
- -## Q. ***What are some of the most popular packages of Node.js?*** - -* **Async**: Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. -* **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 `