Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.
Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, real-time applications that run across distributed devices.
Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications.
Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js.
Q2. Features of Node.js?
Asynchronous and Event Driven
Very Fast
Single Threaded
No Buffering
Non-Blocking I/O model
Everything is asynchronous
Q3. How does Node.js work?
Clients send requests to the webserver to interact with the web application. Requests can be non-blocking or blocking
Perform CRUD operations
Node.js retrieves the incoming requests and adds those to the Event Queue
Requests are passed one-by-one through the Event Loop. It checks if the requests are simple enough not to require any external resources like setTimeout, DOM Manipulation or API
The Event Loop processes simple requests (non-blocking operations), I/O Polling, and returns the responses to the corresponding clients.
Here Client Request is a call to one or more Java Script Functions. Java Script Functions may call other functions or may utilize its Callback functions nature.
Q4. What is REPL?
Node.js Read-Eval-Print-Loop (REPL) is an easy-to-use command-line tool, used for processing Node.js expressions.
It captures the user’s JavaScript code inputs, interprets, and evaluates the result of this code.
It displays the result to the screen, and repeats the process till the user quits the shell.
It is also important to note that this tool does not require file creation to write code. REPL comes ready to use with the Node.js development environment.
write below code in CLI tool or Git bash
node (Enter)
const name = (value) => { console.log(`My name is ${value}`) };
name('Raman'); After that ctrl + D
Q5. How to check all property and methods of Nodejs?
open CLI or Git bash and write:
node (Press Enter)
press 2 times Tab
fs (for check inner property of File System)
// synchronously
const read_data = fs.readFileSync("read.txt");
// console.log(read_data); // It returns only binary data, so we have to use a toString function for it to read for humans
In synchronous you need to wait for a task to finish to move to the next one.
In asynchronous you can move to another task before the previous one finishes.
This way, with asynchronous programming you’re able to deal with multiple requests simultaneously.
Use Cases
If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.
In Asynchronous way you can show some Progress indicator to the user while in background you can continue with your heavy weight works. This is an ideal scenario for GUI apps.
Q14. How to get OS details?
With the help of os module.
console.log(os.type());
Q15. What is nodemon?
The nodemon Module is a module that develop node. js based applications by automatically restarting the node application when file changes in the directory are detected.
Monitors for any changes in your Node.js application
Automatically restarts the server,
Saving time and tedious work.
It's one way to make your development efficient with Opn:
npm install -g nodemon
Q16. Is there any mysql package for MySQL DB?
Yes
Q17. What are Streams in Nodejs?
Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, 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. For example, some of the commonly used events are −
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.
const Stream = require('stream')
const readableStream = new Stream.Readable()
readableStream.push('ping!')
Q18. What is Buffer?
The Buffer class in Node. js is designed to handle raw binary data. It stores temporary storage in RAM. If our data is small peace than we can use Buffer.
In javascript, there are no any machanism to read binary data so that why we used Buffer class. It is used for fast transaction data, and its memory is very less so that's why we should use small peace of data.
var buf = Buffer.from('xyz');
console.log(buf);
Q19. What is piping in Node.js?
The readable.pipe() method in a Readable Stream is used to attach a Writable stream to the readable stream so that it consequently switches into flowing mode and then pushes all the data that it has to the attached Writable.
Q20. What is a test pyramid in Node.js?
The testing pyramid is a concept that groups software tests into three different categories. This helps developers and QA professionals ensure higher quality, reduce the time it takes to find the root cause of bugs, and build a more reliable test suite.
Unit tests (small tests)
Integration tests (medium tests)
End to end tests or e2e tests (large tests)
Q21. What is a first class function in Javascript?
When functions can be treated like any other variable then those functions are first-class functions. Now because of this function can be passed as a param to another function (callback) or a function can return another function (higher-order function).
function sayHi() {
return "Hi, ";
}
function greeting(hiMessage, name) {
console.log(hiMessage() + name);
} // Pass `sayHi` as an argument to `greeting` function greeting(sayHi, "Good Morning!"); // Hi, Good Morning!
Q22. What is event loop?
The event loop is what allows Node.js to perform non-blocking I/O operations. When Node.js starts, it initializes the event loop, which may make async API calls.
Each phase has a FIFO queue of callbacks to execute.
Features of Event Loop:
Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks.
The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task.
The event loop allows us to use callbacks and promises.
The event loop executes the tasks starting from the oldest first.
There have 3 stages like: Call Stack, Node API (API Call, DOM manipulation and timeout function) and Callback queue.
Q23. Node js is single or multithread?
Node. js is a proper multi-threaded language just like Java. There are two threads in Node. js, one thread is dedicatedly responsible for the event loop and the other is for the execution of your program.
But during execution it's support only single thread that's why we call Nodejs is single thread language.
Nodejs is based on Javascript and javascript is based on the single thread so Node js is single thread as well.
Q24. What is jwt?
JWT, or JSON Web Token, is an open standard used to share security information between two parties — a client and a server.
Each JWT contains encoded JSON objects, including a set of claims. JWTs are signed using a cryptographic algorithm to ensure that the claims cannot be altered after the token is issued. We set the signing algorithm to be SHA256 (JWT supports multiple algorithms).
In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:
Header
Payload
Signature
/* ============== Set JWT Token ============== */
let jwtSecretKey = process.env.JWT_SECRET_KEY;
let data = {
time: Date(),
userId: 12,
}
const token = jwt.sign(data, jwtSecretKey);
let jwtSecretKey = process.env.JWT_SECRET_KEY;
const verified = jwt.verify(token, jwtSecretKey);
Q25. What is middleware?
As name suggests it comes in middle of something and that is request and response cycle.
Middleware has access to next function of request-response life cycle
Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware in the stack.
What is this next()?
As a third argument you have another function which you should call once your middleware code completed, otherwise it will get stuck in infinite loop
Q26. What are the alternates ways to handle asynchronous code in node?
A callback function is called after a given task. It allows other code to be run in the meantime and prevents any blocking.
Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks.
Q30. What is fork in node JS?
A fork in general is used to spawn child processes.
In node it is used to create a new instance of v8 engine to run multiple workers to execute the code.
Q31. How many types of API functions are there in Node.js?
Asynchronous, non-blocking functions
Synchronous, blocking functions
Q32. How would you define the term I/O?
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
The term I/O is used to describe any program, operation, or device that transfers data to or from a medium and to or from another medium
Q33. What is package.json?
The package.json file in Node.js is the heart of the entire application. It is basically the manifest file that contains the metadata of the project where we define the properties of a package.
If you plan to publish your package, the most important things in your package.json are the name and version fields as they will be required
This file is used to give information to npm that allows it to identify the project as well as handle the project's dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project.
Q34. What do you understand by Event-driven programming?
Event-driven programming is an approach that heavily makes use of events for triggering various functions. An event can be anything like a mouse click, key press, etc. When an event occurs, a call back function is executed that is already registered with the element.
Because of event-driven programming, Node.js is faster when compared to other technologies.
Q35. What is an Event Emitter 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();
NPM stands for Node Package Manager, responsible for managing all the packages and modules for Node.js.
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
Q37. What is a thread pool?
In Node, there are two types of threads: one Event Loop and another one is Thread Pool.
The libuv library maintains a pool of threads that are used by node.js to perform long-running operations in the background, without blocking its main thread.
libuv is a multi-platform C library that provides support for asynchronous I/O-based operations such as file systems, networking, and concurrency.
Q38. What is the difference between Node.js, AJAX, and JQuery?
Node.js is a javascript runtime that makes it possible for us to write back-end of applications.
Asynchronous JavaScript and XML(AJAX) refers to group of technologies that we use to send requests to web servers and retrieve data from them without reloading the page.
Jquery is a simple javascript library that helps us with front-end development.
Q39. For Node.js, why Google uses V8 engine?
Google uses V8 as it is a Chrome runtime engine that converts JavaScript code into native machine code.
This, in turn, speeds up the application execution and response process and give you a fast running application.
V8 was first designed to increase the performance of JavaScript execution inside web browsers.
Q40. Why is Node.js preferred over other backend technologies like Java and PHP?
Node.js is very fast
Easy for web developersto start using Node.js in their projects as it is a JavaScript library
Perfect for data-intensive, real-time web applications, as Node.js never waits for an API to return data
Better synchronization of code between server and client due to same code base
Node Package Manager has 50,000 + bundles available at the developer’s disposal
Q41. Which database is more popularly used with Node.js?
MongoDB is the most common database used with Node.js. It is a NoSQL, cross-platform, document-oriented database that provides high performance, high availability, and easy scalability.
Q42. Explain the working of the control flow function?
Control flow function is basically the code that is executed between the asynchronous function calls.
Firstly, the order of execution must be controlled.
Then, the required data need to be collected.
Next, the concurrency must be limited.
Once done, the next step of the program has to be invoked.
Q43. What are the pros and cons of Node.js?
Pros
Cons
Uses JavaScript, which is well-known amongst developers.
Using callback is complex since you end up with nested callbacks.
Node Package Manager has 50,000 + packages.
Dealing with relational databases is not a good option for Node.js.
Fast processing and an event-based model.
Not suitable for heavy computational tasks.
Best suited for streaming huge amounts of data.
Since Node.js is single-threaded, CPU intensive tasks are not its strong point.
Q44. What is the use of NODE_ENV?
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.
Q45. How assert works in Node.js?
The assert module provides a way of testing expressions. If the expression evaluates to 0, or false, an assertion failure is being caused, and the program is terminated.
This module was built to be used internally by Node.js.
const assert = require('assert');
assert(40 > 65, "40 is less than 65.");
Q46. 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.
Express. js is a web application framework for Node. js. It provides various features that make web application development fast and easy which otherwise takes more time using only Node.
Express is a flexible Node.js web application framework that provides a wide set of features to develop both web and mobile applications.
Easy to integrate with different template engines like Jade, Vash, EJS, HBS etc.
Allows you to define routes of your application based on HTTP methods and URLs.
Includes various middleware modules which you can use to perform additional tasks on request and response.
Allows you to define an error handling middleware.
Easy to configure and customize.
Easy to serve static files and resources of your application.
Allows you to create REST API server.
Makes Node.js web application development fast and easy.
Easy to connect with databases such as MongoDB, Redis, MySQL
npm install -g express
Q48. List down the various timing features of Node.js?
setTimeout/clearTimeout
setInterval/clearInterval
setImmediate/clearImmediate
process.nextTick
Q49. 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, etc.
Exit codes in Node.js are a specific group of codes that finish off processes, which can include global objects as well. Some of the exit codes in Node.js are -
Fatal Error
Internal Exception
Internal JavaScript Evaluation Failure
Unused
Uncaught fatal exception
handler Run-time failure
Q51. 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.
Cookie Policy
This website uses cookie or similar technologies, to enhance your browsing experience and provide personalised recommendations. By continuing to use our website, you agree to our Cookie Policy.