What is node.js?
Node.js is a Server side scripting which is used to build scalable programs. Its multiple advantages over other server side languages, the prominent being non-blocking I/O.
What are the features of Node.js?
Here is the main features and advantages of node js is,
- Asynchronous and Event Driven
- Very Fast
- Single Threaded but Handling multiple threads at a time.
- No Buffering
Callbacks in Node Js
Callback is a asynchronous function. It will execute in asynchronous manner. In node js heavily used callback functions for non blocking. And also execute parallel.
Callback function example :
function sum(a,b,callback){ callback(a+b); } sum(2,3,function(result){ console.log(result); });
What is callback hell? How can callback hells be avoided in Node.js?
Callback hell in Node.js is a situation which occurs when one tries to execute multiple asynchronous methods one by one simultaneously. There are three major methods which can be used to avoid callback hells in Node.js:
- Using Promises
- Using Async.js
- Using Async-wait
Where can we use node.js?
Node.js can be used for the following purposes
a) Web applications ( especially real-time web apps )
b) Network applications
c) Distributed systems
d) General purpose applications
Can you access DOM in node?
No, you cannot access DOM in node.
What is the difference between Node.js vs Ajax?
The difference between Node.js and Ajax is that, Ajax (short for Asynchronous Javascript and XML) is a client side technology, often used for updating the contents of the page without refreshing it. While,Node.js is Server Side Javascript, used for developing server software. Node.js does not execute in the browser but by the server.
Mention the framework most commonly used in node.js?
"Express" is the most common framework used in node.js
What are Global objects in Node.js?
Node.js has some Global Objects which are available in all modules. Some of these objects are not actually in global scope but in the module scope.
__dirname: The directory name of the current module. This the same as the path.dirname() of the __filename.
__filename: The file name of the current module. This is the resolved absolute path of the current module file.
exports: A reference to the module.exports that is shorter to type. exports is not actually a global but rather local to each module.
require: To require modules. require is not actually a global but rather local to each module.
How node.js works?
Node.js works on a v8 environment, it is a virtual machine that utilizes JavaScript as its scripting language and achieves high output via non-blocking I/O and single threaded event loop.
What are the main disadvantages of using Node.js?
Some of the disadvantages are:
Unstable API and Inconsistencies: One of the biggest disadvantages of Node.js is that it lacks consistency. Node.js’ API changes frequently, and the changes are often backward-incompatible.
Not Suitable for Heavy-Computing Apps: Node.js doesn’t support multi-threaded programming yet. It is able to serve way more complicated applications than Ruby, but it’s not suitable for performing long-running calculations.
Event Driven Model: Event driven model will confuse a lot of programmers who are new to JavaScript. The callback chain can get very long which makes it harder to maintain.
What do you mean by the term I/O ?
I/O is the shorthand for input and output, and it will access anything outside of your application. It will be loaded into the machine memory to run the program, once the application is started.
What does event-driven programming mean?
In computer programming, event driven programming is a programming paradigm in which the flow of the program is determined by events like messages from other programs or threads. It is an application architecture technique divided into two sections
1) Event Selection
2) Event Handling
function addToCart(productId){ event.send("cart.add", {id: productId}); } event.on("cart.add", function(event){ show("Adding product " + event.id); });
What are the two types of API functions in Node.js ?
The two types of API functions in Node.js are
a) Asynchronous, non-blocking functions
b) Synchronous, blocking functions
What is control flow function?
A generic piece of code which runs in between several asynchronous function calls is known as control flow function.
Explain the steps how "Control Flow" controls the functions calls?
a) Control the order of execution
b) Collect data
c) Limit concurrency
d) Call the next step in program
Why Node.js is single threaded?
For async processing, Node.js was created explicitly as an experiment. It is believed that more performance and scalability can be achieved by doing async processing on a single thread under typical web loads than the typical thread based implementation.
Does node run on windows?
Yes – it does. Download the MSI installer from http://nodejs.org/download/
Using the event loop what are the tasks that should be done asynchronously?
a) I/O operations
b) Heavy computation
c) Anything requiring blocking
Why node.js is quickly gaining attention from JAVA programmers?
Node.js is quickly gaining attention as it is a loop based server for JavaScript. Node.js gives user the ability to write the JavaScript on the server, which has access to things like HTTP stack, file I/O, TCP and databases.
What are the two arguments that async.queue takes?
The two arguments that async.queue takes
a) Task function
b) Concurrency value
What is an event loop in Node.js?
To process and handle external events and to convert them into callback invocations an event loop is used. So, at I/O calls, node.js can switch from one request to another .
Mention the steps by which you can async in Node.js?
By following steps you can async Node.js
a) First class functions
b) Function composition
c) Callback Counters
d) Event loops
What are the pros and cons of Node.js?
Pros:
a) If your application does not have any CPU intensive computation, you can build it in Javascript top to bottom, even down to the database level if you use JSON storage object DB like MongoDB.
b) Crawlers receive a full-rendered HTML response, which is far more SEO friendly rather than a single page application or a websockets app run on top of Node.js.
Cons:
a) Any intensive CPU computation will block node.js responsiveness, so a threaded platform is a better approach.
b) Using relational database with Node.js is considered less favourable
Differentiate between process.nextTick() and setImmediate()?
Both can be used to switch to an asynchronous mode of operation by listener functions.
process.nextTick() sets the callback to execute but setImmediate pushes the callback in the queue to be executed. So the event loop runs in the following manner
Does Node.js provide any Debugger?
Node.js do provide a simple TCP based protocol and debugging client that comes built-in. In order to debug your JavaScript file, you can use the below debug argument followed by js file name that you want to debug.
node debug [script.js | -e "script" | <host> : <port> ]
In case you are facing any challenges with these Node.js Interview Questions, please mention your problems in the section comment section below.
Describe the exit codes of Node.js.
In Node.js, exit codes are a set of specific codes which are used for finishing a specific process. These processes can include the global object as well. Below are some of the exit codes used in Node.js:
- Uncaught fatal exception
- Unused
- Fatal Error
- Internal Exception handler Run-time failure
- Internal JavaScript Evaluation Failure
Is cryptography supported in Node.js?
Yes, Node.js does support cryptography through a module called Crypto. This module provides various cryptographic functionalities like cipher, decipher, sign and verify functions, a set of wrappers for open SSL’s hash HMAC etc. For example:
const crypto = require'crypto'); const secret = 'akerude'; const hash = crypto.createHmac('swaEdu', secret).update('Welcome to Edureka').digest('hex'); console.log(hash);
Explain the concept of Punycode in Node.js?
In Node.js, Punycode is an encoding syntax that is used for converting Unicode (UTF-8) string of characters into a basic ASCII string of characters. It is important as the hostnames can only understand the ASCII characters. Thus, Node.js version 0.6.2 onwards, it was bundled up with the default Node package. If you want to use it with any previous versions, you can easily do that by using the following code:
Syntax:
punycode = require('punycode');
Differentiate between readFile vs createReadStream in Node.js?
Node.js provides two ways to read and execute files which are using readFile and CreateStream. readFile() is a fully buffered process which returns the response only when the complete file is pushed into the buffer and is read. It is a memory intensive process and in case of large files, the processing can be very slow. Whereas createReadStream is a partially buffered which treats the entire process as an event series. The entire file is split into chunks which are then processed and sent back as a response one by one. Once done, they are finally removed from the buffer. Unlike readFile, createReadStream is really effective for the processing of the large files.
What is the use of NODE_ENV?
If the project is in the production stage, Node.js promotes the convention of making use of NODE_ENV variable to flag it. This helps in taking better judgment during the development of the projects. Also, when you set your NODE_ENV to production, your application tends to perform 3 times faster.
Explain stream in Node.js along with its various types.
Streams in Node.js are the collection of data similar to arrays and strings. They are objects using which you can read data from a source or write data to a destination in a continuous manner. It might not be available at once and need not to have fit in the memory. These streams are especially useful for reading and processing a large set of data. In Node.js, there are four fundamental types of streams:
- Readable: Used for reading large chunks of data from the source.
- Writeable: Use for writing large chunks of data to the destination.
- Duplex: Used for both the functions; read and write.
- Transform: It is a duplex stream that is used for modifying the data.
How does Node.js handle the child threads?
In general, Node.js is a single threaded process and doesn’t expose the child threads or thread management methods. But you can still make use of the child threads using spawn() for some specific asynchronous I/O tasks which execute in the background and don’t usually execute any JS code or hinder with the main event loop in the application. If you still want to use the threading concept in your application you have to include a module called ChildProcess explicitly.
What is an error-first callback in Node.js?
Error-first callbacks in Node.js are used to pass errors and data. The very first parameter you need to pass to these functions has to be an error object while the other parameters represent the associated data. Thus you can pass the error object for checking if anything is wrong and handle it. In case there is no issue, you can just go ahead and with the subsequent arguments.
var myPost = new Post({title: 'edureka'}); myPost.save(function(err,myInstance){ if(err){ //handle error and return } //go ahead with `myInstance` });
Explain the purpose of module.exports?
A module in Node.js is used to encapsulate all the related codes into a single unit of code which can be interpreted by shifting all related functions into a single file. For example, suppose you have a file called greet.js that contains the two functions as shown below:
module.exports = { greetInHindi: function(){ return "NAMASTE"; }, greetInKorean: function(){ return "ANNYEONGHASEYO"; }};
As you can see module.exports provide two functions which can be imported in another file using below code:
var eduGreets = require ("./greet.js"); eduGreets.greetInHindi() //NAMASTE eduGreets.greetInKorean() //ANNYEONGHASEYO
What do you understand by Reactor Pattern in Node.js?
Reactor Pattern in Node.js is basically a concept of non-blocking I/O operations. This pattern provides a handler that is associated with each I/O operation and as soon as an I/O request is generated, it is then submitted to a demultiplexer. This demultiplexer is a notification interface which is capable of handling concurrency in non-blocking I/O mode. It also helps in collecting each and every request in the form of an event and then place each event in a queue. Thus resulting in the generation of the Event Queue. Simultaneously, we have our event loop which iterates the events present in the Event Queue.
List down the major security implementations within Node.js?
Major security implementations in Node.js are:
- Authentications
- Error Handling
Explain libuv.
Libuv is a multi-platform support library of Node.js which majorly is used for asynchronous I/O. It was primarily developed for Node.js, with time it is popularly practiced with other systems like as Luvit, pyuv, Julia, etc. Libuv is basically an abstraction around libev/ IOCP depending on the platform, providing users an API based on libev. A few of the important features of libuv are:
- Full-featured event loop backed
- File system events
- Asynchronous file & file system operations
- Asynchronous TCP & UDP sockets
- Child processes
Explain the concept of middleware in Node.js?
In general, middleware is a function receives the Request and Response objects. In other words, in an application’s request-response cycle these functions have access to various request & response objects along with the next function of the cycle. The next function of middleware is represented with the help of a variable, usually named next. Most commonly performed tasks by the middleware functions are:
- Execute any type of code
- Update or modify the request and the response objects
- Finish the request-response cycle
- Invoke the next middleware in the stack
What do you understand by ESLint?
ESLint is an open source project initially developed by Nicholas C. Zakas in 2013 which aims to provide a linting utility for JavaScript through a plug. Linters in Node.js are good tools for searching certain bug classes, especially those which are related to the variable scope.
Differentiate between spawn() and fork() methods in Node.js?
In Node.js, the spawn() is used to launch a new process with the provided set of commands. This method doesn’t create a new V8 instance and just one copy of the node module is active on the processor. When your child process returns a large amount of data to the Node you can invoke this method.
child_process.spawn(command[, args][, options])
Whereas, the fork() in Node.js is a special instance of spawn() that executes a new instance of the V8 engine. This method simply means that multiple workers are running on a single Node code base for various task.
child_process.fork(modulePath[, args][, options])
In case you are facing any challenges with these Node.js Interview Questions, please mention your problems in the section comment section below.
Explain the concept of stub in Node.js.
In Node.js, stubs are basically the programs or functions that are used for stimulating the module or component behavior. During any test cases, stubs provide the canned answers of the functions.
Define the concept of the test pyramid. Explain the process to implement them in terms of HTTP APIs.
The test pyramid is basically a concept that is developed by Mike Cohn. According to this, you should have a higher number of low-level unit tests as compared to high-level end-to-end tests that running through a GUI.
In terms of HTTP APIs it may be defined as:
- A higher number of low-level unit tests for each model
- Lesser integration tests to test model interactions
- Lesser acceptance tests for testing actual HTTP endpoints
Explain the purpose of ExpressJS package?
Express.js is a framework built on top of Node.js that facilitates the management of the flow of data between server and routes in the server-side applications. It is a lightweight and flexible framework that provides a wide range of features required for the web as well as mobile application development. Express.js is developed on the middleware module of Node.js called connect. The connect module further makes use of http module to communicate with Node.js. Thus, if you are working with any of the connect based middleware modules, then you can easily integrate with Express.js.
Explain the usage of a buffer class in Node.js?
Buffer class in Node.js is used for storing the raw data in a similar manner of an array of integers. But it corresponds to a raw memory allocation that is located outside the V8 heap. It is a global class that is easily accessible can be accessed in an application without importing a buffer module. Buffer class is used because pure JavaScript is not compatible with binary data. So, when dealing with TCP streams or the file system, it’s necessary to handle octet streams.
How does Node.js handle the child threads?
In general, Node.js is a single-threaded process and doesn’t expose the child threads or thread management methods. But you can still make use of the child threads using spawn() for some specific asynchronous I/O tasks which execute in the background and don’t usually execute any JS code or hinder with the main event loop in the application. If you still want to use the threading concept in your application you have to include a module called ChildProcess explicitly.
Explain the concept of URL module.
The URL module of Node.js provides various utilities for URL resolution and parsing. It is a built-in module that helps in splitting up the web address into a readable format:
var url = require('url');
For ex:
var url = require('url'); var adrs = 'http://localhost:8082/default.htm?year=2019&month=april'; var q = url.parse(adr, true); console.log(q.host); //returns 'localhost:8082' console.log(q.pathname); //returns '/default.htm' console.log(q.search); //returns '?year=2019 and month=april' var qdata = q.query; //returns an object: { year: 2019, month: 'april' } console.log(qdata.month); //returns 'april'