Node.js
What is Node.js?
- Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine, designed to build scalable network applications.
- How does Node.js work?
- Node.js operates on a single-threaded event loop architecture that uses non-blocking I/O operations to handle multiple connections concurrently.
- What are the key features of Node.js?
- Asynchronous and Event-Driven, Fast Execution, Single-Threaded but Highly Scalable, No Buffering, Cross-Platform.
- Explain the concept of Event Loop in Node.js.
- The event loop is the mechanism that handles asynchronous operations in Node.js. It allows Node.js to perform non-blocking I/O operations by offloading tasks to the system kernel whenever possible.
- What is NPM?
- NPM (Node Package Manager) is the default package manager for Node.js, which helps in installing, sharing, and managing dependencies for Node.js projects.
- How to install a package using NPM?
npm install <package-name>
- What is a callback function in Node.js?
- A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
- Explain the concept of Promises in Node.js.
- Promises are used to handle asynchronous operations. They represent a value that may be available now, in the future, or never.
- What are async/await in Node.js?
async/await
are syntactic sugars built on top of Promises.async
functions return a Promise, andawait
is used to wait for the Promise to resolve or reject.
- What is the purpose of the
module.exports
in Node.js?module.exports
is used to export functions, objects, or primitives from a given module so that they can be used in other modules.
- What is the difference between
require
andimport
?require
is used in CommonJS modules, whereasimport
is used in ES6 modules.
- Explain the concept of middleware in Node.js.
- Middleware functions are functions that have access to the request object (
req
), the response object (res
), and the next middleware function in the application’s request-response cycle.
- Middleware functions are functions that have access to the request object (
- How does the EventEmitter work in Node.js?
- The
EventEmitter
class is used to handle events. It allows one to create, fire, and listen for events.
- The
- What are streams in Node.js?
- Streams are objects that let you read data or write data continuously. They can be readable, writable, duplex, or transform streams.
- Explain the concept of clustering in Node.js.
- Clustering is a way to create multiple instances of the Node.js application that can run on multiple CPU cores, thus improving the performance by handling more requests concurrently.
- How do you handle errors in Node.js?
- Errors in Node.js can be handled using try-catch blocks, event emitters, or by checking for error objects in callback functions.
- What is REPL in Node.js?
- REPL stands for Read-Eval-Print-Loop. It is a simple, interactive computer programming environment that takes single user inputs, evaluates them, and returns the result to the user.
- What is a buffer in Node.js?
- Buffers are used to store binary data in Node.js. They are similar to arrays but are used for handling binary data.
- What is the purpose of
process.nextTick()
in Node.js?process.nextTick()
is used to defer the execution of a function until the next iteration of the event loop.
- What is the difference between
setImmediate()
andprocess.nextTick()
?setImmediate()
schedules a callback to execute in the next iteration of the event loop, whereasprocess.nextTick()
defers the execution to the very next iteration of the event loop.
- Explain the purpose of the
path
module in Node.js.- The
path
module provides utilities for working with file and directory paths.
- The
- How do you read a file in Node.js?
- Using the
fs.readFile()
method from thefs
module.
- Using the
- What is the purpose of the
http
module in Node.js?- The
http
module is used to create an HTTP server that listens to server ports and gives a response back to the client.
- The
- What are the core modules in Node.js?
- Core modules are modules included with Node.js, such as
fs
,http
,path
,os
,crypto
, etc.
- Core modules are modules included with Node.js, such as
- How do you create a simple HTTP server in Node.js?
- Using the
http.createServer()
method and specifying a request handler function.
- Using the
- What is the difference between
readFile
andcreateReadStream
in Node.js?readFile
reads the entire file into memory before making it available, whilecreateReadStream
reads the file in chunks, making it suitable for large files.
- What is a package.json file?
- The
package.json
file is the central repository for the configuration of your project, which includes metadata relevant to the project and also includes the list of dependencies.
- The
- How do you handle asynchronous code in Node.js?
- Using callbacks, Promises, and async/await.
- What is the purpose of
fs
module in Node.js?- The
fs
module is used to interact with the file system, allowing for reading, writing, and manipulating files and directories.
- The
- What is a microservice in Node.js?
- A microservice is a small, independent service that communicates over well-defined APIs. Microservices architecture structures an application as a collection of loosely coupled services.
- What is PM2?
- PM2 is a production process manager for Node.js applications that allows you to keep applications alive forever, reload them without downtime, and manage various aspects of running processes.
- What is a promise chain?
- A promise chain is a series of
.then()
methods where each one is executed sequentially, allowing for a series of asynchronous operations to be handled in order.
- A promise chain is a series of
- What is
dns
module in Node.js?- The
dns
module contains functions for performing DNS queries, resolving domain names, and handling DNS servers.
- The
- What is
process.env
in Node.js?process.env
is an object containing the user environment variables.
- Explain the concept of callback hell.
- Callback hell refers to the situation where callbacks are nested within other callbacks several levels deep, making the code hard to read and maintain.
- What is the
zlib
module in Node.js?- The
zlib
module provides compression functionality for gzip and deflate algorithms.
- The
- What are global objects in Node.js?
- Global objects are objects that are available in all modules, such as
global
,process
,console
,Buffer
,__dirname
, and__filename
.
- Global objects are objects that are available in all modules, such as
- What is the difference between
__dirname
and__filename
?__dirname
is the directory name of the current module, while__filename
is the file name of the current module.
- What is
util
module in Node.js?- The
util
module provides various utility functions such as formatting strings, deprecating functions, and debugging.
- The
- What is the purpose of
cluster
module in Node.js?- The
cluster
module allows you to create child processes that share the same server ports, useful for exploiting multi-core systems.
- The
- How do you install a specific version of a package using NPM?
npm install <package-name>@<version>
- What is a REPL Server in Node.js?
- A REPL Server allows you to run a Read-Eval-Print Loop (REPL) in your Node.js application.
- What is the purpose of
os
module in Node.js?- The
os
module provides operating system-related utility methods and properties.
- The
- How do you create a child process in Node.js?
- Using the
child_process
module methods likeexec
,spawn
, orfork
.
- Using the
- What is the
v8
module in Node.js?- The
v8
module provides access to the V8 engine’s statistics and can be used for heap snapshots and other V8-specific tasks.
- The
- Explain the concept of streams and pipes in Node.js.
- Streams are used to handle reading/writing files, network communications, or any kind of end-to-end information exchange. Pipes are used to connect the output of one stream to the input of another.
- What is a daemon process in Node.js?
- A daemon process runs in the background and is detached from the user interface.
- What is the use of
crypto
module in Node.js?- The
crypto
module provides cryptographic functionality that includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign, and verify functions.
- The
Sure, here are some common interview questions and their answers regarding Node.js and Express.js:
Node.js
- What is Node.js?
- Answer: Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to run JavaScript on the server-side. It is built on Chrome’s V8 JavaScript engine and uses an event-driven, non-blocking I/O model, making it efficient and suitable for real-time applications.
- How does Node.js handle asynchronous operations?
- Answer: Node.js handles asynchronous operations using a single-threaded event loop and callback functions. When an asynchronous operation is performed, Node.js will offload it to the event loop and continue executing other code. Once the operation is complete, a callback function is called to handle the result.
- What is the purpose of the
package.json
file in a Node.js project?
- Answer: The
package.json
file is a manifest file that contains metadata about the project, including the project name, version, description, main file, scripts, and dependencies. It is used to manage the project’s dependencies and scripts and provides information to npm.
- What is the difference between
process.nextTick()
andsetImmediate()
?
- Answer:
process.nextTick()
schedules a callback function to be invoked in the same phase of the event loop, before the next I/O event.setImmediate()
schedules a callback function to be executed in the next iteration of the event loop, after the current I/O event has completed.
- How can you handle errors in Node.js?
- Answer: Errors in Node.js can be handled using:
- Try-catch blocks for synchronous code.
- Callback functions that take an error parameter for asynchronous code.
- Promises and
async/await
for handling asynchronous operations. - Global error handlers for uncaught exceptions and unhandled promise rejections.
Express.js
- What is Express.js?
- Answer: Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It simplifies the development of server-side applications by providing a suite of middleware to handle HTTP requests, responses, and routing.
- How do you create a basic Express.js application?
- Answer:
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
- What are middleware functions in Express.js?
- Answer: Middleware functions are functions that have access to the request object (
req
), the response object (res
), and the next middleware function in the application’s request-response cycle. They can perform various tasks such as executing code, modifying the request and response objects, ending the request-response cycle, and calling the next middleware function.
- How do you handle routing in Express.js?
- Answer: Routing in Express.js is handled using the
app.METHOD()
functions, whereMETHOD
is an HTTP method (e.g.,GET
,POST
,PUT
,DELETE
). Routes define how an application responds to client requests for specific endpoints.app.get('/users', (req, res) => { res.send('GET request to the /users endpoint'); }); app.post('/users', (req, res) => { res.send('POST request to the /users endpoint'); });
- How do you serve static files in Express.js?
- Answer: Static files (such as images, CSS, and JavaScript files) can be served using the built-in middleware
express.static
.const express = require('express'); const app = express(); app.use(express.static('public')); app.listen(3000, () => { console.log('Server running on port 3000'); });
- What is the difference between
app.use()
andapp.all()
in Express.js?
- Answer:
app.use()
is used to mount middleware functions that are executed for every request to the app, regardless of the HTTP method or route.app.all()
is used to handle all HTTP methods (GET, POST, PUT, DELETE, etc.) for a specific route.app.use((req, res, next) => { console.log('Middleware for all routes'); next(); }); app.all('/example', (req, res) => { res.send('Handling all HTTP methods for /example'); });
- How do you handle errors in Express.js?
- Answer: Errors in Express.js can be handled using error-handling middleware functions. These functions have four arguments:
err
,req
,res
, andnext
.javascript app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong!'); });
These are just a few questions and answers to help you prepare for a Node.js and Express.js interview. Let me know if you need more detailed explanations or additional questions!