1. Why is Node.js Single-threaded? Ans- Node.js is single-threaded for async processing. By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved as opposed to the typical thread-based implementation. 2. What is callback hell in Node.js? Ans- Callback hell is the result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain. For example: query(“SELECT clientId FROM clients WHERE clientName=’picanteverde’;”, function(id){ query(“SELECT * FROM transactions WHERE clientId=” + id, function(transactions){ transactions.each(function(transac){ query(“UPDATE transactions SET value = ” + (transac.value*0.1) + ” WHERE id=” + transac.id, function(error){ if(!error){ console.log(“success!!”); }else{ console.log(“error”); } }); }); }); }); 3. How can you avoid callback hells? Ans – There are lots of ways to solve the issue of callback hells: o modularization: break callbacks into independent functions o use a control flow library, like async o use generators with Promises • use async/await 4. What’s a stub? Name a use case! Ans – Stubs are functions/programs that simulate the behaviors of components/modules. Stubs provide canned answers to function calls made during test cases. 5. What’s a test pyramid? Give an example! Ans- A test pyramid describes the ratio of how many unit tests, integration tests and end-to-end test you should write. An example for an HTTP API may look like this: • lots of low-level unit tests for models (dependencies are stubbed), • fewer integration tests, where you check how your models interact with each other (dependencies are not stubbed), • less end-to-end tests, where you call your actual endpoints (dependencies are not stubbed). 6. How can you secure your HTTP cookies against XSS attacks? Ans- XSS occurs when the attacker injects executable JavaScript code into the HTML response. To mitigate these attacks, you have to set flags on the set-cookie HTTP header: • HttpOnly – this attribute is used to help prevent attacks such as cross-site scripting since it does not allow the cookie to be accessed via JavaScript. • secure – this attribute tells the browser to only send the cookie if the request is being sent over HTTPS. So it would look something like this: Set-Cookie: sid=; HttpOnly. If you are using Express, with express-cookie session, it is working by default. 7. How can you make sure your dependencies are safe? Ans -When writing Node.js applications, ending up with hundreds or even thousands of dependencies can easily happen. For example, if you depend on Express, you depend on 27 other modules directly, and of course on those dependencies’ as well, so manually checking all of them is not an option! The only option is to automate the update / security audit of your dependencies. For that there are free and paid options: • npm outdated • Trace by RisingStack • NSP • GreenKeeper • Snyk 8. Explain the role of REPL in Node.js. Ans -As the name suggests, REPL (Read Eval print Loop) performs the tasks of – Read, Evaluate, Print and Loop. The REPL in Node.js is used to execute ad-hoc Javascript statements. The REPL shell allows entry to javascript directly into a shell prompt and evaluates the results. For the purpose of testing, debugging, or experimenting, REPL is very critical. 9. Name the types of API functions in Node.js. Ans- There are two types of functions in Node.js.: • Blocking functions – In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously For example: const fs = require(‘fs’); const data = fs.readFileSync(‘/file.md’); // blocks here until file is read console.log(data); // moreWork(); will run after console.log The second line of code blocks the execution of additional JavaScript until the entire file is read. moreWork () will only be called after Console.log • Non-blocking functions – In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted. Non-blocking functions execute asynchronously. For example: const fs = require(‘fs’); fs.readFile(‘/file.md’, (err, data) => { if (err) throw err; console.log(data); }); // moreWork(); will run before console.log Since fs.readFile () is non-blocking, moreWork () does not have to wait for the file read to complete before being called. This allows for higher throughput. 10. Which is the first argument typically passed to a Node.js callback handler? Ans- Typically, the first argument to any callback handler is an optional error object. The argument is null or undefined if there is no error. Error handling by a typical callback handler could be as follows: function callback(err, results) { // usually we’ll check for the error before handling results if(err) { // handle error somehow and return } // no error, perform standard callback handling } 11. What are the functionalities of NPM in Node.js? Ans -NPM (Node package Manager) provides two functionalities: • Online repository for Node.js packages • Command line utility for installing packages, version management and dependency management of Node.js packages 12. What is the difference between Node.js and Ajax? Ans- Node.js and Ajax (Asynchronous JavaScript and XML) are the advanced implementation of JavaScript. They all serve completely different purposes. Ajax is primarily designed for dynamically updating a particular section of a page’s content, without having to update the entire page. Node.js is used for developing client-server applications. 13. Explain chaining in Node.js Ans- Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations. 14. What are “streams” in Node.js? Explain the different types of streams present in Node.js. Ans -Streams are objects that allow reading of data from the source and writing of data to the destination as a continuous process. There are four types of streams. • to facilitate the reading operation • to facilitate the writing operation • to facilitate both read and write operations • is a form of Duplex stream that performs computations based on the available input 15. What are exit codes in Node.js? List some exit codes. Ans-Exit codes are specific codes that are used to end a “process” (a global object used to represent a node process). Examples of exit codes include: • Unused • Uncaught Fatal Exception • Fatal Error • Non-function Internal Exception Handler • Internal Exception handler Run-Time Failure • Internal JavaScript Evaluation Failure 16. What are Globals in Node.js? Ans-Three keywords in Node.js constitute as Globals. These are: • Global – it represents the Global namespace object and acts as a container for all other objects. • Process – It is one of the global objects but can turn a synchronous function into an async callback. It can be accessed from anywhere in the code and it primarily gives back information about the application or the environment. • Buffer – it is a class in Node.js to handle binary data. 17. What is the difference between AngularJS and Node.js? Ans-Angular.JS is a web application development framework while Node.js is a runtime system 18. Why is consistent style important and what tools can be used to assure it? Ans-Consistent style helps team members modify projects easily without having to get used to a new style every time. Tools that can help include Standard and ESLint. 19. Explain modules in node.js. Ans-Modules are reusable block of code whose existence does not impact other code in any way. It is not supported by Javascript. Modules are introduced in ES6. Modules are important for Maintainability, Reusability, and Namespacing of Code. 20. For what require() is used in Node.js? Ans-require() is used to include modules from external files in Node Js. It is the easiest way to include a module in Node. Basically require is a function that takes a string parameter which contains the location of the file that you want to include. It reads the entire javascript file, executes the file, and then proceeds to return the exports object. 21. In which Language Node Js is written ? Ans-Node js is written in C, C++,JavaScript.It uses Google’s open source V8 Javascript Engine to convert Javascript code to C++. 22. Explain what is libuv in Node Js ? Ans- libuv is a multi-platform support library with a focus on asynchronous I/O.It was primarily developed for use by Node.js, but it’s also used by Luvit, Julia, pyuv, and others. When the node.js project began in 2009 as a JavaScript environment decoupled from the browser, it is using Google’s V8 and Marc Lehmann’s libev, node.js combined a model of I/O – evented – with a language that was well suited to the style of programming; due to the way it had been shaped by browsers. As node.js grew in popularity, it was important to make it work on Windows, but libev ran only on Unix. libuv was an abstraction around libev or IOCP depending on the platform, providing users an API based on libev. In the node-v0.9.0 version of libuv libev was removed. Some of the features of libuv are: • Full-featured event loop backed by epoll, kqueue, IOCP, event ports. • Asynchronous TCP and UDP sockets • Asynchronous file and file system operations • Child processes • File system events 23. Why Zlib is used in Node js ? Ans- Zlib is Cross-platform data compression library. It was written by Jean-loup Gailly and Mark Adler. In Node js, you can Zlib for Threadpool, HTTP requests, and responses compression and Memory Usage Tuning. In order to use zlib in node js, you need to install node-zlib package. After installation below is sample code to use Zlib. var Buffer = require(‘buffer’).Buffer; var zlib = require(‘zlib’); var input = new Buffer(‘lorem ipsum dolor sit amet’); var compressed = zlib.deflate(input); var output = zlib.inflate(compressed); 24. How Node js read the content of a file? Ans- Normally NodeJs reads the content of a file in non-blocking, asynchronous way. Node Js uses its fs core API to deal with files. The easiest way to read the entire content of a file in nodeJs is with fs.readFile method. Below is sample code to read a file in NodeJs asynchronously and synchronously. Reading a file in node asynchronously/ non-blocking var fs = require(‘fs’); fs.readFile(‘DATA’, ‘utf8’, function(err, contents) { console.log(contents); }); console.log(‘after calling readFile’); Reading a file in node asynchronously/blocking var fs = require(‘fs’); var contents = fs.readFileSync(‘DATA’, ‘utf8’); console.log(contents); 25. What are Streams? List types of streams available in Node Js ? Ans- Streams are pipes that let you easily read data from a source and pipe it to a destination. Simply put, a stream is nothing but an EventEmitter and implements some specials methods. Depending on the methods implemented, a stream becomes Readable, Writable, or Duplex (both readable and writable). For example, if we want to read data from a file, the best way to do it from a stream is to listen to data event and attach a callback. When a chunk of data is available, the readable stream emits a data event and your callback executes. Take a look at the following snippet: Types of streams are: Readable, Writable, Duplex and Transform. 26. What’s the first argument passed to a Node Js callback handler? Ans-In Node Js all core modules, as well as most of the community-published modules, follows a pattern where the first argument to any callback handler is an error object. this object is optional, if there is no error then in that case null or undefined is passed to the callback. Example of the callback function function callback(err, results) { // usually we’ll check for the error before handling results if(err) { // handle error somehow and return } // no error, perform standard callback handling } 27. Explain the difference between readFile and createReadStream in Node js ? Ans-readFile — is for asynchronously reads the entire contents of a file. It will read the file completely into memory before making it available to the User. readFileSync is synchronous version of readFile. createReadStream — It will read the file in chunks of the default size 64 kb which is specified before hand. 28. What is JIT and how is it related to Node JS ? Ans-JIT stands for Just-in-time. A JIT compiler is a program which is used to send bytecode (it consists of instruction that can be interpreted) to the processor by converting it into instruction. After you have done with writing a program, the compiler compiles the source language statements into bytecode instead of compiling it into the code that carries the information which is similar to the specific hardware platform’s processor. Relation of JIT with Node: Virtual machine of Nodejs has JIT compilation which improves the execution speed of the code. The virtual machine takes the source code and converts to machine code in runtime. By this, the hot functions which are called very often are compiled to machine code and, hence increasing speed. 29. How to create a simple server in Node js that returns Hello World ? Ans-By writing following line of code, you can create a server in Node Js. var http =require(‘http’); http.createServer(function(req,res){ res.writeHead(200,{‘Content-Type’:’text/plain’}); res.end(‘Hello World\n’); }).listen(1320,’127.0.0.3′); 30. what is Closures? A Closure is a function defined within another scope that has access to all the variables within the outer scope. Global variables can be made local (private) with closures. 31. How to use aggregation in Mongoose? Ans-Aggregations are a set of functions that are used to manipulate the data that has been returned from a MongoDB query. In Mongoose, aggregations work as a pipeline. The aggregate function accepts the array of data transformations which are applied by data using different methods in terms of arguments. Syntax: db.customers.aggregate([ … aggregation steps go here …]); In above, aggregation is applied to data of customers. 32. What is difference between put and patch? Ans-The main difference between the put and the patch is Put Patch The embedded entity is believed to the modified version of the resources that are deposited on the original server. It is requested to the client to replace the stored is substituted. In this, the information regarding the way of modifying the original server which has the resources to produce a new version is found. At the time of updating the resource, you need to forward full payload as the request. At the time of updating the resource, you only need to send the parameter of the resource which you want to update. 33. List types of Http requests? Ans-Http defines a set of request methods to perform the desired actions. These request methods are: 1. GET: The GET method asked for the representation of the specifies resource. This request used to retrieve the data. 2. POST: The POST technique is utilized to present an element to the predetermined resource, generally causing a change in state or reactions on the server. 3. HEAD: The HEAD method is similar to the GET method but asks for the response without the response body. 4. PUT: This method is used to substitute all current representations with the payload. 5. DELETE: It is used to delete the predetermined resource. 6. CONNECT: This request is used to settle the TCP/IP tunnel to the server by the target resource 7. OPTION: This method is used to give back the HTTP strategies to communicate with the target resource. 8. TRACE: This method echoes the message which tells the customer how much progressions have been made by an intermediate server. 9. PATCH: The PATCH method gives partial modifications to a resource. 34. What is the revealing module pattern? Ans-Revealing module pattern is similar to Module Pattern.IT ExposES only the properties and methods you want via an returned Object. var greeting = ‘Hello world’ function greet() { console.log(greeting) } module.exports = { greet: greet } 35. What are CommonJs Modules ? Ans-CommonJS Modules is the Standard how to code modules are structured. It specifies an ecosystem for JavaScript outside on the server or for native desktop applications. 36. Explain event loop in Node Js ? 37. Who is the author of Node Js ? Ans-Node Js is written by Ryan Dahl. 38. What is Tracing in Node.js? Ans-Tracing provides a mechanism to collect tracing information generated by V8, Node core and userspace code in a log file. Tracing can be enabled by passing the –trace-events-enabled flag when starting a Node.js application. The set of categories for which traces are recorded can be specified using the –trace-event-categories flag followed by a list of comma separated category names. By default the node and v8 categories are enabled. Running Node.js with tracing enabled will produce log files that can be opened in the chrome://tracing tab of Chrome. 39. How will you debug an application in Node.js? Ans-Node.js includes a debugging utility called debugger. To enable it start the Node.js with the debug argument followed by the path to the script to debug. Inserting the statement debugger; into the source code of a script will enable a breakpoint at that position in the code: 40. Why use Node.js? Ans-Node.js makes building scalable network programs easy. Some of its advantages include: • It is generally fast • It almost never blocks • It offers a unified programming language and data type • Everything is asynchronous • It yields great concurrency 41. Explain module.exports in Node Js ? ANS-The method or variable defined in modules cannot be directly accessible by the outer world, that means you cannot call a module member from the external file. In order to access module member, we need to export the functions or variables of modules using module.exports method. Syntax and usage: // greet.js var greet=function(){ console.log(“hello World”); } module.exports=greet; //In app.js var greet=require(‘./greet.js’); greet(); 42. Is it free to use Node.js? ANS-Yes! Node.js is released under the MIT license and is free to use. 43. What are the benefits of using Node.js? ANS- Following are main benefits of using Node.js • Asynchronous and Event DrivenAll APIs of Node.js library are asynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call. • Very Fast Being built on Google Chrome’s V8 JavaScript Engine, Node.js library is very fast in code execution. • Single Threaded but highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps server to respond in a non-bloking ways and makes server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and same program can services much larger number of requests than traditional server like Apache HTTP Server. • No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. 44. What is the difference of using var and not using var in REPL while dealing with variables? ANS-Use variables to store values and print later. if var keyword is not used then value is stored in the variable and printed. Whereas if var keyword is used then value is stored but not printed. You can use both variables later. 45. What is global installation of dependencies? ANS-Globally installed packages/dependencies are stored in /npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. To install a Node project globally use -g flag. 46. What is local installation of dependencies? ANS-By default, npm installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require(). 47. How to uninstall a dependency using npm? ANS-Use following command to uninstall a module. C:\Nodejs_WorkSpace>npm uninstall dependency-name 48. How to update a dependency using npm? ANS-Update package.json and change the version of the dependency which to be updated and run the following command. C:\Nodejs_WorkSpace>npm update 49. What is Event Emmitter? ANS-EventEmitter class lies in events module. It is accessibly via following syntax − //import events module var events = require(‘events’); //create an eventEmitter object var eventEmitter = new events.EventEmitter(); When an EventEmitter instance faces any error, it emits an ‘error’ event. When new listener is added, ‘newListener’ event is fired and when a listener is removed, ‘removeListener’ event is fired. 50. What is Piping in Node? ANS- Piping is a mechanism to connect output of one stream to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations. Consider the above example, where we’ve read test.txt using readerStream and write test1.txt using writerStream. Now we’ll use the piping to simplify our operation or reading from one file and writing to another file. -DARSHANA RAJPUT SRIEIT]]>