Explain nodejs?
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.
Node.js is made of Chrome V8 engine which is written in C++ and Libuv which is a multi-platform C library that provides support for asynchronous I/O based events on event loops and thread loops.
What is Middleware?
Middleware is a peace of code, a function in node.js, that acts as a bridge between some parts of your code.
Middleware comes in between your request and business logic. It is mainly used to capture logs and enable rate limit, routing, authentication, basically whatever that is not a part of business logic. There are third-party middleware also such as body-parser and you can write your own middleware for a specific use case.
Say you want to log the IP of the client on each request:
Log the client IP on every request
app.use(function (req, res, next) {
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log('Client IP:', ip);
next();
});
Notice that each middleware has 3 parameters:
- req: contain all the requests objects like URLs, path, …
- res: is the response object where we can send the reply back to the client.
- next: continue with the next middleware in the chain.
Default Express 4.0 middlewares
- morgan: logger
- body-parser: parse the body so you can access parameters in requests in req.body. e.g. req.body.name.
- cookie-parser: parse the cookies so you can access parameters in cookies req.cookies. e.g. req.cookies.name.
- serve-favicon: exactly that, serve favicon from route /favicon.ico. Should be call on the top before any other routing/middleware takes place to avoids unnecessary parsing.
Other ExpressJS Middlewares
The following middlewares are not added by default, but it’s nice to know they exist at least:
- compression: compress all request. e.g. app.use(compression())
- session: create sessions. e.g. app.use(session({secret: 'Secr3t'}))
- method-override: app.use(methodOverride('_method')) Override methods to the one specified on the _method param. e.g. GET /resource/1?_method=DELETE will become DELETE /resource/1.
- response-time: app.use(responseTime()) adds X-Response-Time header to responses.
- errorhandler: Aid development, by sending full error stack traces to the client when an error occurs. app.use(errorhandler()). It is good practice to surround it with an if statement to check process.env.NODE_ENV === 'development'.
- vhost: Allows you to use different stack of middlewares depending on the request hostname. e.g. app.use(vhost('*.user.local', userapp)) and app.use(vhost('assets-*.example.com', staticapp)) where userapp and staticapp are different express instances with different middlewares.
- csurf: Adds a Cross-site request forgery (CSRF) protection by adding a token to responds either via session or cookie-parser middleware. app.use(csrf());
- timeout: halt execution if it takes more that a given time. e.g. app.use(timeout('5s'));. However you need to check by yourself under every request with a middleware that checks if (!req.timedout) next();.
Explain the concept of middleware in Node.js.
Middleware is a function that receives the request and response objects. Most tasks that the middleware functions perform are:
- Execute any code
- Update or modify the request and the response objects
- Finish the request-response cycle
- Invoke the next middleware in the stack
What is Git?
Git is a free and open source distributed version control system designed to handle everything from small to large projects with speed and efficiency.
What are the advantages of using promises instead of callbacks?
The main advantage of using promise is you get an object to decide the action that needs to be taken after the async task completes. This gives more manageable code and avoids callback hell.
What is callback hell?
- Callback hell, also known as the pyramid of doom, is the result of intensively nested, unreadable, and unmanageable callbacks, which in turn makes the code harder to read and debug
- improper implementation of the asynchronous logic causes callback hell
Explain the main reasons of using nodejs.
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
What does the runtime environment mean in Node.js?
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.
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 Queue
- Starts process that Client Request
- If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client.
- If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach
- Checks Threads availability from Internal Thread Pool
- Picks up one Thread and assign this Client Request to that thread.
- That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop
- Event Loop in turn, sends that Response to the respective Client.
Name the types of API functions in Node.js?
There are two types of API functions in Node.js:
* Asynchronous, Non-blocking functions
* Synchronous, Blocking functions
**1. 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*:
```javascript
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
**2. 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.
*Example*:
```javascript
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.
How would you define the term I/O?
The term I/O is used to describe any program, operation, or device that transfers data to or from medium and to or from another medium
Every transfer is an output from one medium and an input into another. The medium can be a physical device, network, or files within a system
How is Node.js most frequently used?
Node.js is widely used in the following applications:
1. Real-time chats
2. Internet of Things
3. Complex SPAs (Single-Page Applications)
4. Real-time collaboration tools
5. Streaming applications
6. Microservices architecture
What is NPM?
NPM stands for Node Package Manager, responsible for managing all the packages and modules for Node.js.
Node Package Manager provides two main functionalities:
- Provides online repositories for node.js packages/modules, which are searchable on search.nodejs.org
- Provides command-line utility to install Node.js packages and also manages Node.js versions and dependencies
What is the command used to import external libraries?
The “require” command is used for importing external libraries. For example - “var http=require (“HTTP”).” This will load the HTTP library and the single exported object through the HTTP variable.
##########################
Intermediate Node.js Questions
#########################
What does event-driven programming mean?
An event-driven programming approach uses events to trigger various functions. An event can be anything, such as typing a key or clicking a mouse button. A call-back function is already registered with the element executes whenever an event is triggered.
What is an Event Loop in Node.js?
Event loops handle asynchronous callbacks in Node.js. It is the foundation of the non-blocking input/output in Node.js, making it one of the most important environmental features.
What is an EventEmitter in Node.js?
EventEmitter is a Node.js class that includes all the objects that are basically capable of emitting events. This can be done by attaching named events that are emitted by the object using an eventEmitter.on() function. Thus whenever this object throws an even the attached functions are invoked synchronously.
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
----------
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.
EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.
------------
- EventEmitter is a class that holds all the objects that can emit events
- Whenever an object from the EventEmitter class throws an event, all attached functions are called upon synchronously
What are the two types of API functions in Node.js?
The two types of API functions in Node.js are:
- Asynchronous, non-blocking functions
- Synchronous, blocking functions
What is the package.json file?
The package.json file is the heart of a Node.js system. This file holds the metadata for a particular project. The package.json file is found in the root directory of any Node application or module
This is what a package.json file looks like immediately after creating a Node.js project using the command: npm init
You can edit the parameters when you create a Node.js project
How do you create a simple Express.js application?
- The request object represents the HTTP request and has properties for the request query string,parameters, body, HTTP headers, and so on
- The response object represents the HTTP response that an Express app sends when it receives an HTTP request
What are streams in Node.js?
Streams are objects that enable you to read data or write data continuously.
There are four types of streams:
Readable – Used for reading operations
Writable − Used for write operations
Duplex − Can be used for both reading and write operations
Transform − A type of duplex stream where the output is computed based on input
How do you create a simple server in Node.js that returns Hello World?
- Import the HTTP module
- Use createServer function with a callback function using request and response as parameters.
- Type “hello world."
- Set the server to listen to port 8080 and assign an IP address
Explain asynchronous and non-blocking APIs in Node.js.
- All Node.js library APIs are asynchronous, which means they are also non-blocking
- A Node.js-based server never waits for an API to return data. Instead, it moves to the next API after calling it, and a notification mechanism from a Node.js event responds to the server for the previous API call
How do we implement async in Node.js?
As shown below, the async code asks the JavaScript engine running the code to wait for the request.get() function to complete before moving on to the next line for execution
What is 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. You can export a module using the module.exports, which allows it to be imported into another file using a required keyword.
What is a callback function in Node.js?
A callback is a function called after a given task. This prevents any blocking and enables other code to run in the meantime
Advanced Node.js Questions
What is REPL in Node.js?
REPL stands for Read Eval Print Loop, and it represents a computer environment. It’s similar to a Windows console or Unix/Linux shell in which a command is entered. Then, the system responds with an output
What is the control flow function?
The control flow function is a piece of code that runs in between several asynchronous function calls.
How does control flow manage the function calls?
What is the buffer class in Node.js?
Buffer class stores raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. Buffer class is used because pure JavaScript is not compatible with binary data
What is piping in Node.js?
Piping is a mechanism used to connect the output of one stream to another stream. It is normally used to retrieve data from one stream and pass output to another stream
What are some of the flags used in the read/write operations in files?
How do you open a file in Node.js?
What is a test pyramid in Node.js?
What are the different types of HTTP requests?
HTTP defines a set of request methods used to perform desired actions. The request methods include:
GET: Used to retrieve the data
POST: Generally used to make a change in state or reactions on the server
HEAD: Similar to the GET method, but asks for the response without the response body
DELETE: Used to delete the predetermined resource
How would you connect a MongoDB database to Node.js?
To create a database in MongoDB:
- Start by creating a MongoClient object
- Specify a connection URL with the correct IP address and the name of the database you want to create
List the various Node.js timing features.
As you prepare for your upcoming job interview, we hope that this comprehensive guide has provided more insight into what types of questions you’ll be asked.
################### ###################### ######################
How do you create a simple server in Node.js that returns Hello World?
var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(3000);
What is the purpose of module.exports?
This is used to expose functions of a particular module or file to be used elsewhere in the project. This can be used to encapsulate all similar functions in a file which further improves the project structure.
If Node.js is single threaded then how does it handle concurrency?
The main loop is single-threaded and all async calls are managed by libuv library.
What is a thread pool and which library handles it in Node.js
The Thread pool is handled by the libuv library. libuv is a multi-platform C library that provides support for asynchronous I/O-based operations such as file systems, networking, and concurrency.
How does Node.js overcome the problem of blocking of I/O operations?
Since the node has an event loop that can be used to handle all the I/O operations in an asynchronous manner without blocking the main function.
So for example, if some network call needs to happen it will be scheduled in the event loop instead of the main thread(single thread). And if there are multiple such I/O calls each one will be queued accordingly to be executed separately(other than the main thread).
Thus even though we have single-threaded JS, I/O ops are handled in a nonblocking way.
What is node.js streams?
Streams are instances of EventEmitter which can be used to work with streaming data in Node.js. They can be used for handling and manipulating streaming large files(videos, mp3, etc) over the network. They use buffers as their temporary storage.
There are mainly four types of the stream:
- Writable: streams to which data can be written (for example, fs.createWriteStream()).
- Readable: streams from which data can be read (for example, fs.createReadStream()).
- Duplex: streams that are both Readable and Writable (for example, net.Socket).
- Transform: Duplex streams that can modify or transform the data as it is written and read (for example, zlib.createDeflate()).
Differences between Axios and Fetch:
Axios
Fetch
Axios has url in request object.
Fetch has no url in request object.
Axios is a stand-alone third party package that can be easily installed.
Fetch is built into most modern browsers; no installation is required as such.
Axios enjoys built-in XSRF protection.
Fetch does not.
Axios uses the data property.
Fetch uses the body property.
Axios’ data contains the object.
Fetch’s body has to be stringified.
Axios request is ok when status is 200 and statusText is ‘OK’.
Fetch request is ok when response object contains the ok property.
Axios performs automatic transforms of JSON data.
Fetch is a two-step process when handling JSON data- first, to make the actual request; second, to call the .json() method on the response.
Axios allows cancelling request and request timeout.
Fetch does not.
Axios has the ability to intercept HTTP requests.
Fetch, by default, doesn’t provide a way to intercept requests.
Axios has built-in support for download progress.
Fetch does not support upload progress.
Axios has wide browser support.
Fetch only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+ (This is known as Backward Compatibility).
axios.get('url')
.then((response) => {
// Code for handling the response
})
.catch((error) => {
// Code for handling the error
})
fetch('path-to-the-resource-to-be-fetched')
.then((response) => {
// Code for handling the response
})
.catch((error) => {
// Code for handling the error
});
!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Concurrency: Multiple things happening at once.
Synchronous file read:
const fs = require('fs');
const data = fs.readFileSync('/file.html'); // blocks here until file is read
console.log(data);
doSomethingElse(); // will run after console.log
Note: In synchronous version if an error is thrown then it will have to be caught else the process will crash.
Asynchronous file read:
const fs = require('fs');
fs.readFile('/file.html', (err, data) => {
if (err) throw err;
console.log(data);
});
doSomethingElse(); // will run before console.log
Note: In asynschronous version author is responsible for choosing the way of error handlling. We should always choose non-blocking version over the blocking varient of the function.
Asynchronous: It means that the different parts of a program can run simultaneously without blocking other parts of that program. Node.js is by design asynchronous.
http is a core module provided by the Node.js for handling the web server connection.
!!!!!!!!!!!!!!!!!!
The program lifecycle from source code to execution:
.js file (source code) ➝ compiled into machine code (based on the CPU it runs)
The system that compiles the javascript files into machine code and also manage the program's memory is called javascript runtime.
Chrome V8 engine originally ran in Chrome web browsers. But later it was used to run the javascript without a browser and that exactly what Node.js is. Node.js is written in C++ and build on top of the Chrome V8 engine which is also written in C++. V8 provides the runtime for the Javascript.
Javascript Program (source code) ➝ Chome V8 Engine (compiles) ➝ Machine Code (X86_64, MIPS, ARM, etc) ➝ Runs on CPU
Javascript program is compiled and the bytecode (machine code) is optimized and finally, the machine code runs on the CPU. All these operations are performed by the V8.
Chrome V8 engine is really fast because it is written in C++.
Main features of the Chrome V8 engine
This engine has the implementation of the ECMAScript, which is the specification of the Javascript language features. For example, it specifies how the function will be defined and how the variable will be declared. V8 is written to understand these specifications to compile and run the javascript.