Top Backend Interview Questions

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime and library for running applications outside the client’s server. It is used for creating server-side applications. Node.js is perfect for data-intensive applications as it uses asynchronous, event-driven architecture.

Node.js is based on the V8 engine, a virtual machine that utilizes JavaScript as its scripting language, achieving high output, non-blocking I/O, and a single-threaded event loop.

Where Can We Use Node.js?

  • Web Applications
  • Distributed Systems
  • Network Applications

The term I/O is used to describe any program, operation, or device that transfers data to or from a medium and to another form.

Frontend vs Backend

  1. Frontend refers to the client side of an application, while back end refers to the server side.
  2. The frontend is the part of the web application that users can see and interact with, while the backend constitutes what happens behind the scenes.
  3. Frontend typically includes everything that contributes to the visual aspect of a web application. It generally includes a web server that communicates with a database server for requests.
  4. HTML, CSS, JavaScript, AngularJS, and ReactJS are some of the essentials of front-end development. Java, PHP, Python, and Node.js are some of the backend development technologies.

What is NPM?

Node Package Manager provides two main functions:

  1. It provides online repositories for Node.js packages, which are searchable on search.nodejs.org.
  2. It also provides a command-line utility tool to install Node.js packages, manage versions, and handle dependencies of Node.js packages.

Modules are like JavaScript libraries that can be used in a Node.js application to include a set of functions.

To include a module in a Node.js application, use the require() function with parentheses containing the name of the module.

Node.js has many modules to provide the basic functionality needed for web applications.

Some Common Core Modules and Descriptions

  • http: Includes classes, methods, and events to create Node.js HTTP servers.
  • util: Includes utility functions useful for developers.
  • fs: Includes events, classes, and methods to deal with file I/O operations.
  • url: Includes methods for URL parsing.
  • querystring: Includes methods to work with query strings.
  • stream: Includes methods to handle streaming data.
  • zlib: Includes methods to compress or decompress files.

Why is Node.js Preferred Over Other Backend Technologies Like Java and PHP?

  • Node.js is really fast.
  • Node Package Manager has over 50,000 bundles at the developer’s disposal.
  • Perfect for data-intensive, real-time web applications as the Node.js server waits for an API to return the data.
  • Better synchronization of code between server and clients due to the same code base.
  • Easy for web developers to start using Node.js in their projects as it is a JavaScript library.

Angular vs Node.js

  • Angular is a front-end development framework. It is a client-side environment.
  • It is written in TypeScript, while Node.js is written in C and C++.
  • Angular is used for building single-page client-side web applications, while Node.js is used for building fast and scalable server-side rendering network applications.
  • AngularJS splits a web application into MVC components, while Node.js generates database queries.

MongoDB

MongoDB is the most popular database used with Node.js. It is a NoSQL, cross-platform, document-oriented database with high performance, high availability, and easy scalability.

Express.js

Express is a flexible Node.js web application framework that provides a wide set of features to develop both web and mobile applications.

Mongoose

Mongoose is also a Node.js web application framework for databases to perform simpler tasks.

What is the Command Used to Import External Libraries?

The command require is used for importing external libraries. For example:

javascriptCopy code

var http = require("http");

Intermediate Node.js Questions

What Does Event-Driven Programming Mean?

Event-driven programming excessively uses events to trigger various functions. An event can be anything, such as pressing a key or clicking a mouse button. A callback function already registered with the event is executed.

What is Event Emitter in Node.js?

Event Emitter is a class that holds all the objects that can emit events. Whenever an object from the EventEmitter class throws an event, all the attached functions are called upon synchronously.

javascriptCopy code

const EventEmitter = require("events"); const myEmitter = new EventEmitter(); myEmitter.on("event", () => { console.log("Event is occurred"); }); myEmitter.emit("event");

What Are the API Functions in Node.js?

There are two types of API functions in Node.js:

  • Asynchronous, Non-Blocking Functions
  • Synchronous, Blocking Functions

What is Package.json?

The package.json file is the heart of a Node.js system. This file holds metadata about a particular project. Package.json is present in the root directory of any Node application or module.

How Can We Create a Simple Server in Node.js That Returns “Hello World”?

We can create a simple server using Node.js using this code:

javascriptCopy code

var http = require("http"); http.createServer(function(req, res) {

res.writeHead(200, {"Content-Type": "text/plain"}); res.end("Hello world\n"); });

All the APIs of Node.js are asynchronous, which means non-blocking.

Node.js is a server that never waits for an API to return data; instead, it moves to the next API after calling it. The notification mechanism of Events of Node.js responds to the server for the previous API call.

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 that can be interpreted by shifting all related functions into a single file.

You can export a module so that it can be implemented in another file using require.

What is a Callback Function in Node.js?

A callback is a function called at the completion of a given task and allows other code to be run in the meantime.

Advanced Node.js Questions

What is REPL in Node.js?

REPL stands for Read, Eval, Print, and Loop, and it represents a computer environment like a window console or Unix/Linux shell where a command is entered, and a system responds with output.

REPL performs the following desired tasks:

  • Read: Read the user’s input, parse the input into JavaScript data structures, and store it in memory.
  • Eval: Take and evaluate the data structure.
  • Print: Print the result.
  • Loop: Loop the above command until the user presses Ctrl + C twice.

What is the Control Flow Function?

A control flow function is a piece of code that runs between several asynchronous functions. It controls the order of execution, collects data, limits concurrency, and calls the next step in a program.

What is the Difference Between fork() and Spawn() Methods in Node.js?

fork() is a particular case of spawn() that generates integers but corresponds to a raw memory allocation outside a function. spawn() function launches a new process with the available set of commands.

In fork(), multiple workers run on a single Node code-based multiple tasks. This method doesn’t generate a new VB instance, and only a single copy of the node module is active on the processor.

What is the Usage of 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 to connect the output of one stream to another stream. It is normally used to get data from one stream and pass the output of that stream to another stream.

What Are Some of the Flags Used in Read/Write Operations in Files?

  • r: Open the file for reading. An exception if the file does not exist.
  • r+: Open file for reading and writing. An exception occurs if the file does not exist.
  • w: Open file for writing. The file is created if it does not exist or truncated.
  • w+: Open file for reading and writing. The file is created if it does not exist or truncated if it does exist.
  • a: Open the file for appending. The file is created if it does not exist.
  • a+: Open the file for reading and appending. The file is created if it does not exist.

How Will You Open a File Using Node.js?

The syntax of opening a file in Node.js is:

javascriptCopy code

fs.open(path, flags[, mode], callback);

What is Callback Hell?

Callback Hell, also known as the Pyramid of Doom, is caused by intensively nested, unreadable, and unmanageable callbacks, which, in turn, makes the code harder to read and debug. It is caused by the improper implementation of asynchronous logic.

What is the Reactor Pattern in Node.js?

Reactor pattern is a concept of non-blocking I/O operations. This pattern provides a handler that is associated with each I/O operation, and as an I/O request is generated, it is then submitted to a demultiplexer.

What is Test Pyramid in Node.js?

A Test Pyramid is a figure that explains the proportion of Unit tests, integrations, and end-to-end tests required for the proper development of a project.

The components of a test pyramid are:

  • Unit test: Tests the individual units of code in isolation.
  • Integration Tests: Tests the individual units are of the integration among dissimilar units.
  • End-to-End (E2E) Tests: Tests the whole system, from the user interface to the data store and back.

Describe the Exit Code of Node.js.

Exit codes are a set of specific codes used in finishing a specific process. Given 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

Explain the Concept of Middleware in Node.js.

Middleware is a function that receives the Request and Response objects. Most performed tasks by the middleware are:

  • Executes any type of Code
  • Updates or modifies the request and the response Objects
  • Finishes the Request-Response cycle.
  • Invokes the next middleware in the stack.

What are the Types of HTTP Requests?

HTTP defines a set of request methods to perform the desired actions.

  • GET: Used to retrieve data.
  • POST: Generally used for causing 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 predetermined resources.

How Would You Connect a MongoDB Database to Node.js?

To create a database in MongoDB:

  • Start by creating a MongoClient object.
  • Then specify a Connection URL with the correct IP address and the name of the database you want to create.

javascriptCopy code

var MongoClient = require("mongodb").MongoClient;

var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {

if (err) throw err; console.log("Database Created"); db.close(); });

What is the Use of NODE_ENV?

NODE_ENV is an environmental variable that stands for Node environment in the Express server. It’s how we set and detect which environment we are in. For example:

bashCopy code

export NODE_ENV=production

List Down Various Timing Features of Node.js

The Timers Module is provided by Node.js, which contains various functions for executing code after a specified period. Various functions provided by this module:

  • setTimeout/clearTimeout: Used to schedule code execution after a designated amount of milliseconds.
  • setInterval/clearInterval: Used to execute a block of code multiple times.
  • setImmediate/clearImmediate: Used to execute code at the end of the current event loop cycle.

SQL Interview Questions

  1. Find the lowest salary from the database.sqlCopy codeSELECT dept, MIN(salary) AS lowest_salary FROM employees GROUP BY dept;
  2. Which query will help you to fetch unique values from a column in a table?sqlCopy codeSELECT DISTINCT column_name FROM table_name;
  3. Write the SQL query to fetch unique departments from the Employee_table.sqlCopy codeSELECT DISTINCT dept FROM employees;
  4. Write an SQL query to fetch the unique values of departments and print their length.sqlCopy codeSELECT DISTINCT dept, LENGTH(dept) AS length_dept FROM employees;
  5. What is the use of the DATEDIFF function in MYSQL?sqlCopy codeSELECT DATEDIFF('2021-04-10', '2021-03-30') AS total_days;
  6. Write an SQL query to display the department that has more than 2 employees.sqlCopy codeSELECT dept, COUNT(emp_id) FROM employee GROUP BY dept HAVING COUNT(emp_id) > 2;
  7. Display the details of employees for all the departments except Marketing.sqlCopy codeSELECT * FROM employees WHERE dept <> 'Marketing';
  8. Write an SQL Query to print the details of the employees who have joined before April 2010 and after May 2005.sqlCopy codeSELECT * FROM employees WHERE doj > '2005-05-31' AND doj < '2010-04-31';
  9. Find the employee with the 3rd Highest Salary from the table.sqlCopy codeSELECT * FROM (SELECT * FROM employees ORDER BY salary LIMIT 3);
  10. Find Alternate records in the table.sqlCopy codeSELECT * FROM employees WHERE emp_id % 2 = 1; SELECT * FROM employees WHERE emp_id % 2 = 0;
  11. Write the Duplicate Query to duplicate rows in the table.sqlCopy codeSELECT e_id, name, age, COUNT(*) AS dup_count FROM dup_employees GROUP BY e_id, name, age HAVING COUNT(e_id) > 1;
  12. Display the employees Having 2 A’s in their name.sqlCopy codeSELECT * FROM employees WHERE LENGTH(REPLACE(UPPER(emp_name), 'A', '')) = LENGTH(UPPER(emp_name)) - 2;
  13. Given a string, how will you extract four characters starting from the second position?sqlCopy codeSELECT SUBSTR('Michael Ballaback', 2, 4);
  14. How does self-join work? Self-join joins a table to itself. The table must contain a column (x) that acts as the primary key and a different column (y) that stores values that can be matched up with the values in column x.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *