Node.js

Ace your homework & exams now with Quizwiz!

Name the types of API functions in Node.js?

Asynchronous, Non-blocking functions Synchronous, Blocking functions

Techniques for avoiding callback hell

Async.js, Promises, Async-Await

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.

What is the difference between operational and programmer errors?

Operation errors are not bugs, but problems with the system, like request timeout or hardware failure. On the other hand programmer errors are actual bugs.

What are the data types in Node.js?

String, Number, Boolean, Undefined, Null, RegExp

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. Features of Stub: 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 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.

What is 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.

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

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

Is Node.js entirely based on a single-thread?

Yes, it is true that Node.js processes all requests on a single thread. But it is just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously. Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers. To explain it practically, let's assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.

What is 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 than 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.

What is difference between put and patch?

PUT and PATCH are HTTP verbs and they both relate to updating a resource. The main difference between PUT and PATCH requests are in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. 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. Also, another difference is that when you want to update a resource with PUT request, you have to send the full payload as the request whereas with PATCH, you only send the parameters which you want to update. The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them. POST - create GET - read PUT - update DELETE - delete PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.

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 command. To come out of NODE REPL, press ctrl+c twice

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

Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port. The cluster module helps to spawn new processes on the operating system. Each process works independently, so you cannot use shared state between child processes. Each process communicates with the main process by IPC and pass server handles back and forth. 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 child process itself listen the port.

What is the difference between Asynchronous and 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.

What tools can be used to assure consistent style?

ESLint, Standard

Explain how does Node.js work?

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. 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. 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.

What is EventEmitter in Node.js?

All objects that emit events are members of 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 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 - 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. 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. 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.

What is the use of DNS module in Node.js?

DNS is a node module used to do name resolution facility which is provided by the operating system as well as used to do an actual DNS lookup. No need for memorising IP addresses - DNS servers provide a nifty solution of converting domain or subdomain names to IP addresses. This module provides an asynchronous network wrapper and can be imported using the following syntax.

Why to use Express.js?

ExpressJS is a prebuilt NodeJS framework that can help you in creating server-side web applications faster and smarter. Simplicity, minimalism, flexibility, scalability are some of its characteristics and since it is made in NodeJS itself, it inherited its performance as well. 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. It has become the standard server framework for node.js. Express is the backend part of something known as the MEAN stack. The MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications which has the following components; MongoDB - The standard NoSQL database Express.js - The default web applications framework Angular.js - The JavaScript MVC framework used for web applications Node.js - Framework used for scalable server-side and networking applications. The Express.js framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests.

When should you npm and when yarn?

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.

What are Promises in 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). 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: 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).

What is a control flow function? what are the steps does it execute?

It is a generic piece of code which runs in between several asynchronous function calls is known as control flow function. It executes the following steps. Control the order of execution. Collect data. Limit concurrency. Call the next step in the program.

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 npm in Node.js?

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. We can verify its version using the following command-

What is Node.js Process Model?

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.

How do Node.js works?

Node is completely event-driven. Basically the server consists of one thread processing one event after another. 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. 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 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: 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. Even 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 QueueStarts process that Client RequestIf 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 approachChecks Threads availability from Internal Thread PoolPicks 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 LoopEvent Loop in turn, sends that Response to the respective Client.

What does emitter do and what is dispatcher?

Node.js core API is based on asynchronous event-driven architecture in which certain kind of objects called emitters periodically emit events that cause listener objects to be called. All objects that emit events are members of 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 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.

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

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. 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.

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 test pyramid? How can you implement it when talking about HTTP APIs?

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.

How Node.js read the content of a file?

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

What is crypto in Node.js? How do you cipher the secure information in Node.js?

The Node.js Crypto module supports cryptography. It provides cryptographic functionality that includes a set of wrappers for open SSL's hash HMAC, cipher, decipher, sign and verify functions. Hash: A hash is a fixed-length string of bits i.e. procedurally and deterministically generated from some arbitrary block of source data. HMAC: HMAC stands for Hash-based Message Authentication Code. It is a process for applying a hash algorithm to both data and a secret key that results in a single final hash.

What does the runtime environment mean 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 Node.js runtime for App Engine in the standard environment is declared in the app.yaml file: runtime: nodejs10 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.

What is Event loop in Node.js? And 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

What is an error-first callback?

The pattern used across all the asynchronous methods in Node.js is called Error-first Callback. Here is an example: fs.readFile( "file.json", function ( err, data ) { if ( err ) { console.error( err ); } console.log( data ); }); 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. 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.

What are globals in Node.js?

There are three keywords in Node.js which constitute as Globals. These are Global, Process, and Buffer. 1. Global The Global keyword represents the global namespace object. It acts as a container for all other global objects. If we type console.log(global), it will print out all of them. An important point to note about the global objects is that not all of them are in the global scope, some of them fall in the module scope. So, it is wise to declare them without using the var keyword or add them to Global object. Variables declared using the var keyword become local to the module whereas those declared without it get subscribed to the global object. 2. Process It is also one of the global objects but includes additional functionality to turn a synchronous function into an async callback. There is no boundation to access it from anywhere in the code. It is the instance of the EventEmitter class. And each node application object is an instance of the Process object. It primarily gives back the information about the application or the environment. <process.execPath> - to get the execution path of the Node app. <process.Version> - to get the Node version currently running. <process.platform> - to get the server platform. Some of the other useful Process methods are as follows. <process.memoryUsage> - To know the memory used by Node application. <process.NextTick> - To attach a callback function that will get called during the next loop. It can cause a delay in executing a function. 3. Buffer The Buffer is a class in Node.js to handle binary data. It is similar to a list of integers but stores as a raw memory outside the V8 heap. We can convert JavaScript string objects into Buffers. But it requires mentioning the encoding type explicitly. <ascii> - Specifies 7-bit ASCII data. <utf8> - Represents multibyte encoded Unicode char set. <utf16le> - Indicates 2 or 4 bytes, little endian encoded Unicode chars. <base64> - Used for Base64 string encoding. <hex> - Encodes each byte as two hexadecimal chars.

What are the security mechanisms available in Node.js?

Using the Helmet module Helmet helps to secure your Express applications by setting various HTTP headers, like: X-Frame-Options to mitigates clickjacking attacks, Strict-Transport-Security to keep your users on HTTPS, X-XSS-Protection to prevent reflected XSS attacks, X-DNS-Prefetch-Control to disable browsers DNS prefetching. Validating user input, Securing your Regular Expressions, Security.txt

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

When to use Node.js It is ideal to use Node.js for developing streaming or event-based real-time applications that require less CPU usage such as. Chat applications. Game servers -- Node.js is good for fast and high-performance servers, that face the need to handle thousands of user requests simultaneously. Good For A Collaborative Environment -- It is suitable 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. Advertisement Servers -- Here again, we have servers that handle thousands of request for downloading advertisements from a central host. And Node.js is an ideal solution to handle such tasks. Streaming Servers -- Another ideal scenario to use Node.js is for multimedia streaming servers where clients fire request's towards the server to download different multimedia contents from it. To summarize, it's good to use Node.js, when you need high levels of concurrency but less amount of dedicated CPU time. Last but not the least, since Node.js uses JavaScript internally, so it fits best for building client-side applications that also use JavaScript. When to not use Node.js However, we can use Node.js for a variety of applications. But it is a single threaded framework, so 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. Hence, Node.js is best when processing needs less dedicated CPU time.


Related study sets

Chapter 7 Ownership of Real Property

View Set

History 1302 Reading quiz 2 review

View Set

NCLEX pediatric youtube questions

View Set

Capital Gains and Losses Part 1 (Wash Sales & Related-Party Transactions)

View Set