Node Interview Questions

Ace your homework & exams now with Quizwiz!

Since node is a single threaded process, how to make use of all CPUs?

-Node.js does support forking multiple processes ( which are executed on different cores ). -It is important to know that state is not shared between master and forked process. -We can pass messages to forked process ( which is different script ) and to master process from forked process with function send. A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load. The cluster module allows easy creation of child processes that all share server ports.

What is the difference between Asynchronous and Non-blocking?

1. Asynchronous The architecture of asynchronous explains that the message sent will not give the reply on immediate basis just like we send the mail but do not get the reply on an immediate basis. It does not have any dependency or order. Hence improving the system efficiency and performance. The server stores the information and when the action is done it will be notified. 2. Non-Blocking Nonblocking immediately responses with whatever data available. Moreover, it does not block any execution and keeps on running as per the requests. If an answer could not be retrieved then in those cases API returns immediately with an error. Nonblocking is mostly used with I/O(input/output). Node.js is itself based on nonblocking I/O model. There are few ways of communication that a nonblocking I/O has completed. The callback function is to be called when the operation is completed. Nonblocking call uses the help of javascript which provides a callback function. Asynchronous VS Non-Blocking Asynchronous does not respond immediately, While Nonblocking responds immediately if the data is available and if not that simply returns an error. 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. 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.

List the steps for Node's Single Threaded Event Loop Model Processing (part of how Node.js works)

1. Client sends a request to the Node.js Web Server. 2. The Web Server internally maintains a Limited Thread pool for handling client requests. 3. When it receives a request, it places it into the Event Queue. 4. The Event Loop then continuously loops through the Event Queue to see if there are any client requests. 5. The Event Loop is Single Threaded. 6. If there are no client requests, then it waits for incoming requests. 7. If there are, then it picks up a Client Request and starts processing it. 8. If the request is non-blocking, everything gets processed and it sends the response back to the client. 9. If request is blocking where it has to interact with a database, file system or external services, it will check for threads available from internal thread pool. 10. It assigns the request to the thread, which processes it and performs the blocking IO operation and then sends response back to the Event loop. 11. The Event Loop then sends the response back to the client.

How to create a simple server in Node.js that returns Hello World?

1. Create project directory -mkdir myapp -cd myapp 2. Initialize project and link it to npm -npm init (creates package.json file that contains references for all npm packages you have downloaded to your project.) set the entry point from index.js to app.js 3. Install Express in myapp dir -npm install express --save 4. modify app.js with route that returns a hello world response. var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(3000, function () { console.log('Example app listening on port 3000!'); }); 5. Run the app node app.js

What are globals in Node.js?

1. Global The Global keyword represents the global namespace object. It acts as a container for all other global objects. Not all global objects are in the global scope, some fall in the module scope. It's wise to declare them without using vary keyword, or add them to Global object. Variables declared using var become local to the module. 2. Process It is also one of the global objects but includes additional functionality to turn a synchronous function into an async callback. Cannot be accessed in the code, it's an instance of the EventEmitter class. Each node application object is an instance of the Process object. It gives back info about the application or environment. process.execPath: to get the execution path of the Node app. process.platform: to get the server platform 3. Buffer A class that handles binary data. It is similar to a list of integers but stores as a raw memory outside the V8 heap. We can convert JS string objects into Buffers by explicitly stating the encoding type. Encoding Types: ascii, utf8, base64, hex...

Name the types of API functions in Node.js?

1. Synchronous, 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. 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 2. Asynchronous, 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. const fs = require('fs'); fs.readFile('/file.md', (err, data) => { if (err) throw err; console.log(data); }); // moreWork(); will run before console.log

Techniques for avoiding callback hell

1. Using Async.js 2. Using Promises 3. Using Async-Await

What is difference between promises and async-await in Node.js?

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed. This way, other operations can keep running without interruption. Await is basically syntactic sugar for Promises. It makes asynchronous code look more like synchronous/procedural code, which is easier for humans to understand. Putting the keyword async before a function tells the function to return a Promise. If the code returns something that is not a Promise, then JavaScript automatically wraps it into a resolved promise with that value. The await keyword simply makes JavaScript wait until that Promise settles and then returns its result.

What are Promises in Node.js?

A promise represents the result of an async operation. It lets you associate handlers to an async action's eventual success or failure. This lets async methods return values like synchronous methods. Instead of a final value, the async method returns a promise for the value at some point in the future. In Node, promises promise to do some work and then have separate callbacks that would be executed for success and failure as well as handling timeouts. They're like emitters that emit only two events: success and errors. You can combine them into dependency chains. Do Promise C only when promise A and B complete. It is in one of three different states: 1. pending - initial state of a promise 2. fulfilled - state of promise representing a successful operation 3. rejected - state representing a failed operation. once fulfilled or rejected it is immutable.

What is the EventEmitter in Node.js?

All objects that emit events are members of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. All values returned by the called listeners are ignored and will be discarded.

What is LTS releases of Node.js why should you care?

An LTS(Long Term Support) version of Node.js receives all the critical bug fixes, security updates and performance LTS versions of Node.js are supported for at least 18 months and are indicated by even version numbers (e.g. 4, 6, 8). They're best for production since the LTS release line is focussed on stability and security, whereas the Current release line has a shorter lifespan and more frequent updates to the code. Changes to LTS versions are limited to bug fixes for stability, security updates, possible npm updates, documentation updates and certain performance improvements that can be demonstrated to not break existing applications.

Describe in words and using code, how to use Async Await to avoid callback hell

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. const getrandomnumber = function(){ return new Promise((resolve, reject)=>{ setTimeout(() => { resolve(Math.floor(Math.random() * 20)); }, 1000); }); } const addRandomNumber = async function(){ const sum = await getrandomnumber() + await getrandomnumber(); console.log(sum); } addRandomNumber();

List ways to use Async.js to avoid callback hell

Async is a powerful npm module for managing asrynchronous processes. to install: npm install --save async 1. Async Waterfall 2. Async Series

Explain step by step using code, how to async in Node.js

Async/Await is the newest way to write asynchronous code in JavaScript. It is non blocking (just like promises and callbacks). It was created to simplify the process of working with and writing chained promises. Async functions return a Promise. If the function throws an error, the Promise will be rejected. If the function returns a value, the Promise will be resolved. Async: async function add(x,y){ return x + y; } Await: function doubleAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x * 2); }, 2000); }); } async function addAsync(x) { const a = await doubleAfter2Seconds(10); const b = await doubleAfter2Seconds(20); const c = await doubleAfter2Seconds(30); return x + a + b + c; } addAsync(10).then((sum) => { console.log(sum); });

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. Express: Express is a fast, minimalist web framework. It provides small, robust tooling for HTTP servers, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs. Lodash: Lodash is a modern JavaScript utility library delivering modularity, performance, & extras.

What are the key features of Node.js?

Asynchronous event driven IO helps concurrent request handling - 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. 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. Node.js library uses JavaScript - The majority of developers are already well-versed in JavaScript for client side development. Hence, development in Node.js becomes easier for a developer who knows JavaScript. 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. No Buffering - Node.js applications never buffer any data. They simply output the data in chunks.

What is callback hell in Node.js?

Callback hell is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the other.

How to handle file upload in Node.js?

Can use the following packages: express: Popular web framework built on top of Node.js, used for creating REST-API. body-parser: Parse incoming request bodies in a middleware multer: Middleware for handling multipart/form-data — file uploads

Why use Express.js?

ExpressJS is a prebuilt NodeJS framework that can help you create server-side web applications faster. It's simple, minimalist, flexible and highly scalable. It's also made in Node so it inherits all of its performance advantages. Express 3.x is a light-weight web application framework to help organize your web application into an MVC architecture on the server side. You can then use a database like MongoDB with Mongoose (for modeling) to provide a backend for your Node.js application. Express.js basically helps you manage everything, from routes, to handling requests and views.

What is your favourite HTTP framework and why?

Express.js Express provides a thin layer on top of Node.js with web application features such as basic routing, middleware, template engine and static files serving, so the drastic I/O performance of Node.js doesn't get compromised. Generator Generates specific project folder structure. After installing express-generator npm package and creating application skeleton with generator command, an application folder with clear hierarchy will be created to help you organize images, front-end static JavaScript, stylesheet files and HTML template files.

Comparing Yarn vs npm

Fast: Yarn caches every package it downloads. It also parallelizes operations to maximize resource utilization so install time is faster. Reliable: Using a detailed but concise lockfile format and a deterministic algorithm for installs, it is able to guarantee an install that worked on one system will work exactly the same way on any other system. Secure: Yarn uses checksums to verify integrity of every installed package before its code is executed Offline mode: If you've installed a package before you can do it again without 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 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

What does the runtime environment mean in Node.js?

The Node.js runtime is the software stack (node version) responsible for installing your web service's code and its dependencies. The runtime environment describes both the hardware (RAM, OS, CPU) and software that your application is running on.

What are the Challenges with Node.js?

If the code is not well-written or if developers use outdated tools, the performance can suffer, and users might experience more bugs and app crashes. On top of that, poor-quality code can hamper the app's scaling capacity and the further development of the application. In the worst case scenario, it might become impossible to introduce new features without rewriting the codebase from scratch. -Extensive stack -Technical Debt -Scalability challanges -Poor documentation How to Deal With Maintenance Problems -Conduct code review -Use microservices -Improve code quality -Test before new feature implementation -Improve documentation -Update the stack -Dig into the roots

What is difference between put and patch?

In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. If you want to update a resource with PUT request, you have to send the full payload as the request whereas with PATCH, you only send the parameters which you want to update.

What is chaining process in Node.js?

It is an approach to connect the output of one stream to the input of another stream, thus creating a chain of multiple stream operations.

What is Node.js?

It is an open-source, cross-platform runtime environment that runs on the V8 engine and provides event-driven, non-blocking (async) I/O to build scalable JavaScript server-side applications outside of a web browser.

How to use JSON Web Token (JWT) for authentication in Node.js?

JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. Advantages of using JWT for authorization: -Purely stateless. -No additional server or infra required to store session information. -It can be easily shared among services. JSON Web Tokens consist of three parts separated by dots (.), which are: jwt.sign(payload, secretOrPrivateKey, [options, callback])

How to build a microservice architecture with Node.js?

Microservice application architecture is built with lightweight protocols and disintegrate the app into smaller services to improve modularity. 1. Create a server to accept requests // server.js const express = require('express') const app = express(); const port = process.env.PORT || 3000; const routes = require('./api/routes'); routes(app); app.listen(port, function() { console.log('Server started on port: ' + port); }); 2. Defining the routes and assign each to a target in the controller. const controller = require('./controller'); module.exports = function(app) { app.route('/about') .get(controller.about); app.route('/distance/:zipcode1/:zipcode2') .get(controller.getDistance); }; 3. Adding Controller Logic Within the controller file, we are going to create a controller object with two properties. Those properties are the functions to handle the requests we defined in the routes module.

Why is npm shrinkwrap useful?

NPM shrinkwrap lets you lock down the versions of installed packages and their descendant packages. It helps you use same package versions on all environments (development, staging, production) and also improve download and installation speed. This will help you test systems and deploy with confidence. If it passes on one machine, it will pass on others since it uses the same code.

What is npm?

NPM stands for Node Package Manager. It provides following two main functionalities. It works as an Online repository for node.js packages/modules which are present at <nodejs.org>. It works as Command line utility to install packages, do version management and dependency management of Node.js packages. NPM comes bundled along with Node.js installable.

How does Node.js work?

Node is completely event-driven. The server consists of one thread processing one event after another. A new request coming in is a kind of event. The server starts processing it and if 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. When the IO operation is finished, that is another kind of event and the server will process it by executing the callback as soon as it has time. The server never needs to create additional threads or switch between threads, which means it has little overhead. If you want to make full use of multiple hardware cores, just start multiple instances of node.js Node platform follows the Single Threaded with Event Loop Model.

If Node.js is single threaded, how does it handle concurrency?

Node uses an event loop to maintain concurrency and perform non-blocking I/O operations. When Node starts, it initializes an event loop. The event loop iterates over an Event Queue and performs the tasks in FIFO order. If it finds a function, it adds it to the call stack. It continuously checks the call stack to see if there are any tasks that need to be run. The stack works in LIFO order. It executes a task when there is no ongoing task in the call stack. Now whenever the event loop finds any function, it adds it to the stack and runs in order.

What is JIT and how is it related to Node.js?

Node.js has depended on the V8 JavaScript engine to provide code execution in the language. The V8 is a JavaScript engine built at the google development center, in Germany. It is open source and written in C++. It is used for both client side (Google Chrome) and server side (node.js) JavaScript applications. A central piece of the V8 engine that allows it to execute JavaScript at high speed is the JIT (Just In Time) compiler. This is a dynamic compiler that can optimize code during runtime. When V8 was first built the JIT Compiler was dubbed FullCodegen. Then, the V8 team implemented Crankshaft, which included many performance optimizations that FullCodegen did not implement. The V8 was first designed to increase the performance of the JavaScript execution inside web browsers. In order to obtain speed, V8 translates JavaScript code into more efficient machine code instead of using an interpreter. It compiles JavaScript code into machine code at execution by implementing a JIT (Just-In-Time) compiler like a lot of modern JavaScript engines such as SpiderMonkey or Rhino (Mozilla) are doing. The main difference with V8 is that it doesn't produce bytecode or any intermediate code.

How does Node.js handle child threads?

Node.js is a single threaded language which in background uses multiple threads to execute asynchronous code. Node.js is non-blocking which means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads. That is handled by Node.js run-time. -Nodejs Primary application runs in an event loop, which is in a single thread. -Background I/O is running in a thread pool that is only accessible to C/C++ or other compiled/native modules and mostly transparent to the JS. -Node v11/12 now has experimental worker_threads, which is another option. -Node.js does support forking multiple processes ( which are executed on different cores ). -It is important to know that state is not shared between master and forked process. -We can pass messages to forked process ( which is different script ) and to master process from forked process with function send.

What are the difference between Events and Callbacks?

Node.js is a single-threaded application, but it support concurrency via the concept of event and callbacks. Callback functions are called when an asynchronous function returns its result, whereas event handling is part of 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 the EventEmitter class which are used to bind events and event-listeners 1. Callback: 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. 2. Events: Every action on a computer is an event. Node allows us to create and handle custom events easily by using the events module. The events module includes the EventEmitter class which can be used to raise and handle custom events.

How does Node.js support multi-processor platforms, and does it fully utilize all processor resources?

Node.js provides support for deployment on multiple-core systems. The Cluster module allows running multiple Node.js worker processes that will share the same port. Each process works independently, so you cannot use shared state between child processes. Each process communicates with the main process by IPC and pass server handles back and forth. The Cluster supports two types of load distribution: The main process listens on a port, accepts new connection and assigns it to a child process in a round robin fashion. The main process assigns the port to a child process and the child process itself listens on the port.

What is the Node.js Process Model?

Node.js runs on a single process and the application code runs on a single thread, thereby it needs less resources than other platforms. All 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. With Async, the single thread doesn't have to wait for the request to complete and is free to handle the next request. When the async I/O work completes then it processes the request further and sends the response.

How Node.js overcomes the problem of blocking of I/O operations?

Node.js solves this problem by putting the event based model at its core, using an event loop instead of threads.

When should you use npm and when should you use yarn?

Npm is the default method for managing packages in Node.js runtime environment. It relies on a command line client and a database made up of public and premium packages known as the npm registry. Yarn was developed by Facebook to resolve some of npm's shortcomings. I't snot a replacement for npm since it relies on modules from npm registry. It's a new installer that still uses the same npm structure, only the installation method is different.

What tools can be used to assure consistent style?

Pluggable tools like ESLint or Standard which are linters that can identify and report on patterns in JavaScript.

Describe how to use promises to avoid callback hell

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. var outputPromise = getInputPromise().then(function (input) { //handle success }, function (error) { //handle error });

What is REPL? What purpose it is used for?

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: 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 com

Explain RESTful Web Services in Node.js?

REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It is an architectural style as well as an approach for communications purposes that is often used in various web services development. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. HTTP methods GET − Provides read-only access to a resource. PUT − Updates an existing resource or creates a new resource. DELETE − Removes a resource. POST − Creates a new resource. PATCH− Update/modify a resource Principles of REST Uniform Interface Stateless Cacheable Client-Server Layered System Code on Demand (optional)

How does routing work in Node.js?

Routing defines the way in which the client requests are handled by the application endpoints. We define routing using methods of the Express app object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post to handle POST requests, app.all() to handle all HTTP methods and app.use() to specify middleware as the callback function. These routing methods "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function. For example, can use either app.get(path, handler) or router.get(path, handler)

How many types of streams are present in node.js?

Streams are objects that let you read data from a source or write data to a destination in continuous fashion. There are four types of streams Readable − Stream which is used for read operation. Writable − Stream which is used for write operation. Duplex − Stream which can be used for both read and write operation. Transform − A type of duplex stream where the output is computed based on input. Each type of Stream is an EventEmitter instance and throws several events at different instance of times. Example: data − This event is fired when there is data is available to read. end − This event is fired when there is no more data to read. error − This event is fired when there is any error receiving or writing data. finish − This event is fired when all the data has been flushed to underlying system.

What is a stub?

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.

How does node.js prevent blocking code?

Synchronous methods in the Node.js standard library that use libuv are the most commonly used blocking operations. Native modules may also have blocking methods. Blocking methods execute synchronously and non-blocking methods execute asynchronously.

How does Node.js read the content of a file?

The "normal" way is to read in the content of a file in a non-blocking, asynchronous way. That is, to tell Node to read in the file, and then to get a callback when the file-reading has been finished. That would allow us to hand several requests in parallel. Common use for the File System module: Read files Create files Update files Delete files Rename files

What is the dispatcher and what does it provide over emitters?

The Dispatcher has functionality not provided nor expected in the EventEmitter class, the most notable being waitFor, which allows a store to ensure that another store has been updated in response to an action before it proceeds. Pattern-wise, the Dispatcher is also a singleton, whereas EventEmitter is an API that you might object-assign onto multiple stores.

What is the Reactor Pattern in Node.js?

The Reactor Pattern is used to avoid the blocking of the I/O operations. It provides us with a handler that is associated with each operation. When I/O requests are generated, they get submitted to a demultiplexer, which handles concurrency and collects the requests as events and queues them up in the EventQueue to be processed by the EventLoop. Steps: 1. Application sends a request to the Event Demultiplexer. Request also specifies a handler which will be invoked with the operation completes. Submitting a request is non-blocking and control is given back to the application. 2. When a set of I/O operations complete, the Event Demultiplexer pushes the new events into the Event Queue. 3. The Event Loop iterates over the items in the Event Queue. For each event, the associated handler is invoked. 4. The handler, which is part of the application code, will give back the control to the Event Loop when its execution completes (5a). 5. However, new asynchronous operations might be requested during the execution of the handler (5b), causing new operations to be inserted in the Event Demultiplexer (1), before the control is given back to the Event Loop. 6. When all the items in the Event Queue are processed, the loop will block again on the Event Demultiplexer which will then trigger another cycle.

How to generate and verify checksum of the given string in Nodejs

The checksum (aka hash sum) calculation is a one-way process of mapping an extensive data set of variable length (e.g., message, file), to a smaller data set of a fixed length (hash). The length depends on a hashing algorithm. For the checksum generation, we can use node crypto() module. The module uses createHash(algorithm) to create a checksum (hash) generator. The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform.

What is an error-first callback in Node.js ?

The error-first pattern consists of executing a function when the asynchronous operation ends. It takes as first argument an error, if one occurred, and the result of the request as extra arguments. Example: fs.readFile( "file.json", function ( err, data ) { if ( err ) { console.error( err ); } console.log( data ); });

What is Event loop in Node.js? How does it work?

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. 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. Event-Driven Programming 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. 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 // Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); // Create an event handler as follows var connectHandler = function connected() { console.log('connection succesful.'); // Fire the data_received event eventEmitter.emit('data_received'); } // Bind the connection event with the handler eventEmitter.on('connection', connectHandler); // Bind the data_received event with the anonymous function eventEmitter.on('data_received', function() { console.log('data received succesfully.'); }); // Fire the connection event eventEmitter.emit('connection'); console.log("Program Ended.");

What is typically the first argument passed to a Node.js callback handler?

The first argument to any callback handler is an optional error object 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 }

How can you make sure your dependencies are safe?

The only option is to automate the update / security audit of your dependencies. For that there are free and paid options: 1. npm audit

What are the data types in Node.js?

There are two types, Primitives and Objects. Primitives -String -Number -Bigint -Boolean -Undefined -Null -Symbol Objects -Function -Array -Buffer: Node.js includes an additional data type called Buffer (not available in browser's JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network. Buffer is a class. -other regular objects

How to load html in Node.js?

To load HTML in Node.js we have to change the "Content-type" in the HTML code from text/plain to text/html.

What is the preferred method of resolving unhandled exceptions in Node.js?

Unhandled exceptions in Node.js can be caught at the Process level by attaching a handler for uncaughtException event. process.on('uncaughtException', function(err) { console.log('Caught exception: ' + err); }); Process is a global object that provides information about the current Node.js process. Process is a listener function that is always listening to events. Few events are : Exit disconnect unhandledException rejectionHandled

When to use Node.js and when not to use it?

Use Node.js Developing streaming or event-based real-time applications that require less CPU usage such as: -Chat applications. -Game servers -- good for fast and high-performance servers that need to handle thousands of user requests simultaneously. -A Collaborative Environment -- good for environments where multiple people work together. For example, they post their documents, modify them by doing check-out and check-in of these documents. Node.js supports such situations by creating an event loop for every change made to the document. The "Event loop" feature of Node.js enables it to handle multiple events simultaneously without getting blocked. To summarize, it's good to use Node.js, when you need high levels of concurrency but less amount of dedicated CPU time. Also best for building client-side applications that use JavaScript since Node uses it internally. Not to use Node.js Since it is a single threaded framework, we should not use it for cases where the application requires long processing time. If the server is doing some calculation, it won't be able to process any other requests.

How to kill child processes that spawn their own child processes in Node.js?

We can start child processes with {detached: true} option so those processes will not be attached to main process but they will go to a new group of processes. Then using process.kill(-pid) method on main process we can kill all processes that are in the same group of a child process with the same pid group.

How can you secure your HTTP cookies against XSS attacks?

When the web server sets cookies, it can provide additional attributes to make sure cookies won't be accessible by using malicious JS. 1. HttpOnly makes sure the cookies will be submitted only to the domain they originated from. Set-Cookie: [name]=[value]; HttpOnly 2. The "Secure" attribute can make sure the cookies are sent over secured channel only. Set-Cookie: [name]=[value]; Secure 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. X-XSS-Protection: 1; mode=block 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. Content-Security-Policy: default-src 'self' *.http://sometrustedwebsite.com

Can you create an http server in Node.js, explain the code used for it?

var http = require('http'); var requestListener = function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Welcome Viewers\n'); } var server = http.createServer(requestListener); server.listen(4200); // The port where you want to start with.

How to make post request in Node.js?

var request = require('request'); request.post('http://www.example.com/action', { form: { key: 'value' } }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) } });


Related study sets

日本語総まとめN2語彙 第1週 1日目

View Set

Chapter 16: Assessment and Care of the Newborn

View Set

Financial Statement Analysis Ch.2

View Set

Market-Based Management Chapter 2: Marketing Metrics and Marketing Profitability, Ch1

View Set