Node.js Interview Master
Master Backend Excellence with 200+ Curated Node.js Questions
What is Node.js?
BeginnerNode.js is a cross-platform, open-source JavaScript runtime environment that executes JavaScript code outside a web browser. It is built on Google Chr...
Comprehensive Answer:
Node.js is a cross-platform, open-source JavaScript runtime environment that executes JavaScript code outside a web browser. It is built on Google Chrome's V8 JavaScript engine.
Is Node.js single-threaded?
BeginnerYes, Node.js is primarily single-threaded for its event loop, but it uses internal worker threads (via libuv) for handling expensive I/O operations li...
Comprehensive Answer:
Yes, Node.js is primarily single-threaded for its event loop, but it uses internal worker threads (via libuv) for handling expensive I/O operations like file system access or network requests.
What is the difference between Node.js and JavaScript?
BeginnerJavaScript is a programming language, whereas Node.js is a runtime environment that allows you to run JavaScript on the server side.
Comprehensive Answer:
JavaScript is a programming language, whereas Node.js is a runtime environment that allows you to run JavaScript on the server side.
What is npm?
Beginnernpm (Node Package Manager) is the default package manager for Node.js. It allows developers to share and reuse code and manage project dependencies.
Comprehensive Answer:
npm (Node Package Manager) is the default package manager for Node.js. It allows developers to share and reuse code and manage project dependencies.
What is REPL in Node.js?
BeginnerREPL stands for Read-Eval-Print Loop. It is an interactive shell that takes user inputs, executes them, and prints the result, useful for testing smal...
Comprehensive Answer:
REPL stands for Read-Eval-Print Loop. It is an interactive shell that takes user inputs, executes them, and prints the result, useful for testing small snippets of code.
What are the core modules of Node.js?
BeginnerCore modules include 'fs' (file system), 'http' (creating servers), 'path' (handling file paths), 'os' (operating system info), and 'events' (event em...
Comprehensive Answer:
Core modules include 'fs' (file system), 'http' (creating servers), 'path' (handling file paths), 'os' (operating system info), and 'events' (event emitters).
How do you create a simple server in Node.js?
BeginnerUsing the 'http' module: `http.createServer((req, res) => { res.end('Hello'); }).listen(3000);`
Comprehensive Answer:
Using the 'http' module: `http.createServer((req, res) => { res.end('Hello'); }).listen(3000);`
What is the role of 'package.json'?
BeginnerIt is the manifest file for a Node.js project. It contains metadata about the project, script definitions, and lists of dependencies and devDependenci...
Comprehensive Answer:
It is the manifest file for a Node.js project. It contains metadata about the project, script definitions, and lists of dependencies and devDependencies.
What is the difference between `require` and `import`?
Beginner`require` is CommonJS syntax used in Node.js by default. `import` is ES6 module syntax. Node.js supports both, but ES6 requires `.mjs` extension or `"...
Comprehensive Answer:
`require` is CommonJS syntax used in Node.js by default. `import` is ES6 module syntax. Node.js supports both, but ES6 requires `.mjs` extension or `"type": "module"` in package.json.
What is a callback function?
BeginnerA callback is a function passed as an argument to another function, which is executed after some operation (usually asynchronous) is completed.
Comprehensive Answer:
A callback is a function passed as an argument to another function, which is executed after some operation (usually asynchronous) is completed.
What is the Event Loop in Node.js?
BeginnerThe Event Loop is a mechanism that allows Node.js to perform non-blocking I/O operations by offloading tasks to the system kernel whenever possible.
Comprehensive Answer:
The Event Loop is a mechanism that allows Node.js to perform non-blocking I/O operations by offloading tasks to the system kernel whenever possible.
What is the difference between `setImmediate()` and `setTimeout()`?
Beginner`setImmediate()` is designed to execute a script once the current poll phase completes. `setTimeout()` schedules a script to be run after a minimum th...
Comprehensive Answer:
`setImmediate()` is designed to execute a script once the current poll phase completes. `setTimeout()` schedules a script to be run after a minimum threshold in ms has elapsed.
What is the purpose of `module.exports`?
BeginnerIt is used to define what a module exports so that it can be used in other files using `require()`.
Comprehensive Answer:
It is used to define what a module exports so that it can be used in other files using `require()`.
What is `process.argv`?
BeginnerIt is an array containing the command-line arguments passed when the Node.js process was launched.
Comprehensive Answer:
It is an array containing the command-line arguments passed when the Node.js process was launched.
Explain 'Non-blocking I/O'.
BeginnerIt means that Node.js doesn't wait for an I/O operation (like reading a file) to finish before moving to the next task. Instead, it provides a callbac...
Comprehensive Answer:
It means that Node.js doesn't wait for an I/O operation (like reading a file) to finish before moving to the next task. Instead, it provides a callback.
What is the `fs` module?
BeginnerThe `fs` (File System) module allows you to interact with the file system on your computer (reading, writing, deleting files).
Comprehensive Answer:
The `fs` (File System) module allows you to interact with the file system on your computer (reading, writing, deleting files).
What is 'Callback Hell'?
BeginnerIt occurs when multiple nested callbacks make the code hard to read and maintain. It's often solved using Promises or Async/Await.
Comprehensive Answer:
It occurs when multiple nested callbacks make the code hard to read and maintain. It's often solved using Promises or Async/Await.
What is a Promise?
BeginnerA Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
Comprehensive Answer:
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
What is Async/Await?
BeginnerIt is a syntactic sugar built on top of Promises that allows you to write asynchronous code that looks and behaves like synchronous code.
Comprehensive Answer:
It is a syntactic sugar built on top of Promises that allows you to write asynchronous code that looks and behaves like synchronous code.
What is Global Object in Node.js?
BeginnerUnlike the browser's `window` object, Node.js has a `global` object. Common globals include `process`, `__dirname`, and `__filename`.
Comprehensive Answer:
Unlike the browser's `window` object, Node.js has a `global` object. Common globals include `process`, `__dirname`, and `__filename`.
Explain `__dirname` and `__filename`.
Beginner`__dirname` is the directory name of the current module. `__filename` is the absolute path of the current module file.
Comprehensive Answer:
`__dirname` is the directory name of the current module. `__filename` is the absolute path of the current module file.
What is the use of 'path' module?
BeginnerThe 'path' module provides utilities for working with file and directory paths (e.g., `path.join()`, `path.extname()`).
Comprehensive Answer:
The 'path' module provides utilities for working with file and directory paths (e.g., `path.join()`, `path.extname()`).
What is 'error-first callback'?
BeginnerIt is a pattern where the first argument of a callback is an error object (if any), and the second argument is the result data.
Comprehensive Answer:
It is a pattern where the first argument of a callback is an error object (if any), and the second argument is the result data.
How do you install a specific version of a package?
BeginnerUsing `npm install <package>@<version>` (e.g., `npm install express@4.17.1`).
Comprehensive Answer:
Using `npm install <package>@<version>` (e.g., `npm install express@4.17.1`).
What is the difference between `dependencies` and `devDependencies`?
Beginner`dependencies` are required for the application to run. `devDependencies` are only needed for development and testing (e.g., nodemon, jest).
Comprehensive Answer:
`dependencies` are required for the application to run. `devDependencies` are only needed for development and testing (e.g., nodemon, jest).
What is 'nodemon'?
BeginnerNodemon is a tool that automatically restarts the Node.js application when file changes in the directory are detected.
Comprehensive Answer:
Nodemon is a tool that automatically restarts the Node.js application when file changes in the directory are detected.
What is 'event-driven' programming?
BeginnerIt is a paradigm where the flow of the program is determined by events such as user actions, sensor outputs, or messages from other programs.
Comprehensive Answer:
It is a paradigm where the flow of the program is determined by events such as user actions, sensor outputs, or messages from other programs.
What is an EventEmitter?
BeginnerA class in the 'events' module used to handle custom events. You can 'emit' events and 'listen' for them using `.on()`.
Comprehensive Answer:
A class in the 'events' module used to handle custom events. You can 'emit' events and 'listen' for them using `.on()`.
What is a Buffer in Node.js?
BeginnerA Buffer is a way to handle binary data in Node.js, specifically used to deal with streams of binary data.
Comprehensive Answer:
A Buffer is a way to handle binary data in Node.js, specifically used to deal with streams of binary data.
What is the purpose of `os` module?
BeginnerThe `os` module provides operating system-related utility methods like `os.platform()`, `os.cpus()`, and `os.totalmem()`.
Comprehensive Answer:
The `os` module provides operating system-related utility methods like `os.platform()`, `os.cpus()`, and `os.totalmem()`.
What is 'Stream' in Node.js?
BeginnerStreams are objects that let you read data from a source or write data to a destination in a continuous fashion.
Comprehensive Answer:
Streams are objects that let you read data from a source or write data to a destination in a continuous fashion.
Name the types of Streams in Node.js.
BeginnerFour types: Readable, Writable, Duplex (both read/write), and Transform (modify data while reading/writing).
Comprehensive Answer:
Four types: Readable, Writable, Duplex (both read/write), and Transform (modify data while reading/writing).
What is 'piping' in streams?
BeginnerPiping is a mechanism to connect the output of a readable stream directly to the input of a writable stream (e.g., `src.pipe(dest)`).
Comprehensive Answer:
Piping is a mechanism to connect the output of a readable stream directly to the input of a writable stream (e.g., `src.pipe(dest)`).
What is 'Chaining' in Node.js?
BeginnerChaining is a mechanism to connect multiple stream operations together (e.g., pipe to zip, then pipe to write file).
Comprehensive Answer:
Chaining is a mechanism to connect multiple stream operations together (e.g., pipe to zip, then pipe to write file).
What is the use of `util.promisify()`?
BeginnerIt is a utility that takes a function following the common error-first callback style and returns a version that returns a promise.
Comprehensive Answer:
It is a utility that takes a function following the common error-first callback style and returns a version that returns a promise.
What is 'Express.js'?
BeginnerExpress is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Comprehensive Answer:
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
What is 'Middleware' in Express?
BeginnerMiddleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the ap...
Comprehensive 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.
How do you handle routing in Express?
BeginnerUsing `app.get()`, `app.post()`, `app.put()`, `app.delete()` etc., or using `express.Router()` for modular routes.
Comprehensive Answer:
Using `app.get()`, `app.post()`, `app.put()`, `app.delete()` etc., or using `express.Router()` for modular routes.
What is 'body-parser'?
BeginnerInitially a separate middleware, now built into Express (`express.json()`). It parses incoming request bodies in a middleware before your handlers.
Comprehensive Answer:
Initially a separate middleware, now built into Express (`express.json()`). It parses incoming request bodies in a middleware before your handlers.
What is 'REST API'?
BeginnerREST (Representational State Transfer) is an architectural style for designing networked applications using standard HTTP methods.
Comprehensive Answer:
REST (Representational State Transfer) is an architectural style for designing networked applications using standard HTTP methods.
What is 'JSON'?
BeginnerJSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read/write and easy for machines to parse/genera...
Comprehensive Answer:
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read/write and easy for machines to parse/generate.
Explain `cors` package.
Beginner`cors` is a Node.js package for providing a Connect/Express middleware that can be used to enable CORS (Cross-Origin Resource Sharing) with various op...
Comprehensive Answer:
`cors` is a Node.js package for providing a Connect/Express middleware that can be used to enable CORS (Cross-Origin Resource Sharing) with various options.
What is `dotenv`?
Beginner`dotenv` is a zero-dependency module that loads environment variables from a `.env` file into `process.env`.
Comprehensive Answer:
`dotenv` is a zero-dependency module that loads environment variables from a `.env` file into `process.env`.
What is 'Mongoose'?
BeginnerMongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, etc.
Comprehensive Answer:
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, etc.
What is 'JWT'?
BeginnerJWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties.
Comprehensive Answer:
JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties.
How to handle file uploads in Node.js?
BeginnerCommonly using libraries like 'multer' which handles 'multipart/form-data'.
Comprehensive Answer:
Commonly using libraries like 'multer' which handles 'multipart/form-data'.
What is 'Bcrypt' used for?
BeginnerBcrypt is a library used to hash passwords securely before storing them in a database.
Comprehensive Answer:
Bcrypt is a library used to hash passwords securely before storing them in a database.
What is 'Validation' in Node.js API?
BeginnerChecking if the input data meets certain criteria (e.g., email format, required fields). Libraries like 'Joi' or 'express-validator' are common.
Comprehensive Answer:
Checking if the input data meets certain criteria (e.g., email format, required fields). Libraries like 'Joi' or 'express-validator' are common.
What is the difference between `null` and `undefined` in JS?
Beginner`undefined` means a variable has been declared but has not yet been assigned a value. `null` is an assignment value representing no value.
Comprehensive Answer:
`undefined` means a variable has been declared but has not yet been assigned a value. `null` is an assignment value representing no value.
What is 'Hoisting'?
BeginnerHoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope before code execution.
Comprehensive Answer:
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope before code execution.
Explain the Event Loop phases.
ExperiencePhases include: Timers (setTimeout), Pending Callbacks, Idle/Prepare, Poll (incoming I/O), Check (setImmediate), and Close Callbacks.
Comprehensive Answer:
Phases include: Timers (setTimeout), Pending Callbacks, Idle/Prepare, Poll (incoming I/O), Check (setImmediate), and Close Callbacks.
What are 'Microtasks' and 'Macrotasks'?
ExperienceMicrotasks (process.nextTick, Promises) run after the current operation finishes and before the next Event Loop phase. Macrotasks (setTimeout, setImme...
Comprehensive Answer:
Microtasks (process.nextTick, Promises) run after the current operation finishes and before the next Event Loop phase. Macrotasks (setTimeout, setImmediate) run in specific phases of the Event Loop.
What is `process.nextTick()`?
Experience`process.nextTick()` adds a callback to the 'next tick queue'. This queue is processed after the current operation completes, regardless of the curren...
Comprehensive Answer:
`process.nextTick()` adds a callback to the 'next tick queue'. This queue is processed after the current operation completes, regardless of the current phase of the event loop.
How does Node.js handle concurrency?
ExperienceNode.js uses an event-driven, non-blocking I/O model. It uses a single thread to handle many connections concurrently by offloading I/O to the kernel/...
Comprehensive Answer:
Node.js uses an event-driven, non-blocking I/O model. It uses a single thread to handle many connections concurrently by offloading I/O to the kernel/worker pool.
Explain 'Clustering' in Node.js.
ExperienceThe 'cluster' module allows you to create child processes (workers) that share the same server port, enabling your app to use all available CPU cores.
Comprehensive Answer:
The 'cluster' module allows you to create child processes (workers) that share the same server port, enabling your app to use all available CPU cores.
What is 'Worker Threads' module?
ExperienceThe `worker_threads` module enables the use of threads that execute JavaScript in parallel, useful for CPU-intensive tasks without blocking the event ...
Comprehensive Answer:
The `worker_threads` module enables the use of threads that execute JavaScript in parallel, useful for CPU-intensive tasks without blocking the event loop.
Difference between Cluster and Worker Threads?
ExperienceCluster creates separate instances of the entire Node.js process (different memory). Worker threads run in the same process and share memory (via Shar...
Comprehensive Answer:
Cluster creates separate instances of the entire Node.js process (different memory). Worker threads run in the same process and share memory (via SharedArrayBuffer).
How to handle memory leaks in Node.js?
ExperienceUsing heap dumps, Chrome DevTools, and monitoring tools to find growing objects that aren't being garbage collected (e.g., global variables, forgotten...
Comprehensive Answer:
Using heap dumps, Chrome DevTools, and monitoring tools to find growing objects that aren't being garbage collected (e.g., global variables, forgotten timers).
Explain 'Backpressure' in Streams.
ExperienceBackpressure occurs when data is written to a stream faster than it can be consumed. Node.js handles this by pausing the readable stream when the writ...
Comprehensive Answer:
Backpressure occurs when data is written to a stream faster than it can be consumed. Node.js handles this by pausing the readable stream when the writable buffer is full.
What is 'libuv'?
ExperienceLibuv is a multi-platform C library that provides support for asynchronous I/O based on event loops. It handles the thread pool, file system, and netw...
Comprehensive Answer:
Libuv is a multi-platform C library that provides support for asynchronous I/O based on event loops. It handles the thread pool, file system, and network I/O in Node.js.
How to secure a Node.js API?
ExperienceUsing 'helmet' for security headers, rate limiting, data validation, avoiding 'eval()', keeping dependencies updated, and using HTTPS.
Comprehensive Answer:
Using 'helmet' for security headers, rate limiting, data validation, avoiding 'eval()', keeping dependencies updated, and using HTTPS.
Explain 'authentication' vs 'authorization'.
ExperienceAuthentication is verifying who a user is (e.g., login). Authorization is verifying what a user is allowed to do (e.g., access levels).
Comprehensive Answer:
Authentication is verifying who a user is (e.g., login). Authorization is verifying what a user is allowed to do (e.g., access levels).
How to scale Node.js applications?
ExperienceHorizontal scaling (adding more servers/instances with Load Balancers) and Vertical scaling (adding more CPU/RAM).
Comprehensive Answer:
Horizontal scaling (adding more servers/instances with Load Balancers) and Vertical scaling (adding more CPU/RAM).
What is 'PM2'?
ExperiencePM2 is a production process manager for Node.js applications. It provides features like auto-restart, cluster mode, and monitoring.
Comprehensive Answer:
PM2 is a production process manager for Node.js applications. It provides features like auto-restart, cluster mode, and monitoring.
Explain 'Socket.io'.
ExperienceSocket.io is a library that enables real-time, bi-directional, and event-based communication between the browser and the server.
Comprehensive Answer:
Socket.io is a library that enables real-time, bi-directional, and event-based communication between the browser and the server.
What is 'Redis' used for in Node.js?
ExperienceRedis is an in-memory data store commonly used as a cache, session store, or message broker to improve performance.
Comprehensive Answer:
Redis is an in-memory data store commonly used as a cache, session store, or message broker to improve performance.
Explain 'Stub', 'Mock', and 'Spy' in testing.
ExperienceSpy: tracks calls to a function. Stub: replaces a function with a version that returns fixed data. Mock: fake object with pre-programmed expectations.
Comprehensive Answer:
Spy: tracks calls to a function. Stub: replaces a function with a version that returns fixed data. Mock: fake object with pre-programmed expectations.
How to perform 'Graceful Shutdown'?
ExperienceListening for SIGTERM/SIGINT signals, stopping the server from accepting new requests, and finishing existing ones before exiting.
Comprehensive Answer:
Listening for SIGTERM/SIGINT signals, stopping the server from accepting new requests, and finishing existing ones before exiting.
Explain 'Domain-Driven Design' (DDD) in Node.js.
ExperienceAn approach to software development that centers the design on a core domain model, fostering a common language between tech and business.
Comprehensive Answer:
An approach to software development that centers the design on a core domain model, fostering a common language between tech and business.
What is 'Microservices Architecture'?
ExperienceDesigning an application as a collection of small, independent services that communicate over APIs (e.g., via HTTP or RabbitMQ).
Comprehensive Answer:
Designing an application as a collection of small, independent services that communicate over APIs (e.g., via HTTP or RabbitMQ).
How to handle distributed tracing?
ExperienceUsing tools like OpenTelemetry, Jaeger, or Zipkin to track requests as they move across different microservices.
Comprehensive Answer:
Using tools like OpenTelemetry, Jaeger, or Zipkin to track requests as they move across different microservices.
Explain 'Event Sourcing'.
ExperienceA pattern where the state of the application is determined by a sequence of events, rather than just the current state in a DB.
Comprehensive Answer:
A pattern where the state of the application is determined by a sequence of events, rather than just the current state in a DB.
What is 'CQRS'?
ExperienceCommand Query Responsibility Segregation—splitting read operations (Queries) and write operations (Commands) into different models.
Comprehensive Answer:
Command Query Responsibility Segregation—splitting read operations (Queries) and write operations (Commands) into different models.
How to optimize expensive database queries?
ExperienceAdding indexes, using projections (selecting only needed fields), pagination, and caching results in Redis.
Comprehensive Answer:
Adding indexes, using projections (selecting only needed fields), pagination, and caching results in Redis.
Explain 'Hydration' in Node.js SSR.
ExperienceThe process of making statically rendered HTML interactive on the client side by attaching event listeners.
Comprehensive Answer:
The process of making statically rendered HTML interactive on the client side by attaching event listeners.
How to handle 10k connections simultaneously?
ExperienceUsing a Load Balancer (Nginx), horizontal scaling, and ensuring the application is stateless.
Comprehensive Answer:
Using a Load Balancer (Nginx), horizontal scaling, and ensuring the application is stateless.
Explain 'Garbage Collection' in V8.
ExperienceV8 uses a generational collector (Scavenge for young objects, Mark-Sweep-Compact for old objects) to reclaim memory.
Comprehensive Answer:
V8 uses a generational collector (Scavenge for young objects, Mark-Sweep-Compact for old objects) to reclaim memory.
What is 'Heap' vs 'Stack' memory?
ExperienceStack is for static data (primitive values, function calls). Heap is for dynamic data (objects, arrays).
Comprehensive Answer:
Stack is for static data (primitive values, function calls). Heap is for dynamic data (objects, arrays).
Explain 'Proto-Pollution' vulnerability.
ExperienceA vulnerability where an attacker manipulates the `__proto__` property to inject properties into all objects in the application.
Comprehensive Answer:
A vulnerability where an attacker manipulates the `__proto__` property to inject properties into all objects in the application.
How to use 'crypto' module?
ExperienceUsed for cryptographic operations like hashing, HMAC, encryption/decryption, and digital signatures.
Comprehensive Answer:
Used for cryptographic operations like hashing, HMAC, encryption/decryption, and digital signatures.
What is 'Passport.js'?
ExperienceAuthentication middleware for Node.js. It supports various 'strategies' like OAuth, Local (username/password), etc.
Comprehensive Answer:
Authentication middleware for Node.js. It supports various 'strategies' like OAuth, Local (username/password), etc.
How to handle large file uploads to S3?
ExperienceUsing 'multipart upload' and 'presigned URLs' to allow the client to upload directly to S3 securely.
Comprehensive Answer:
Using 'multipart upload' and 'presigned URLs' to allow the client to upload directly to S3 securely.
Explain 'serverless' with Node.js.
ExperienceDeploying individual functions (Lambdas) that run in response to events, without managing the underlying server infrastructure.
Comprehensive Answer:
Deploying individual functions (Lambdas) that run in response to events, without managing the underlying server infrastructure.
What is 'Cold Start' in Serverless?
ExperienceThe delay that occurs when a serverless function is triggered for the first time or after a period of inactivity.
Comprehensive Answer:
The delay that occurs when a serverless function is triggered for the first time or after a period of inactivity.
Explain 'GRPC'.
ExperienceA high-performance RPC framework that uses Protocol Buffers and HTTP/2 for efficient cross-service communication.
Comprehensive Answer:
A high-performance RPC framework that uses Protocol Buffers and HTTP/2 for efficient cross-service communication.
What is 'GraphQL'?
ExperienceA query language for APIs that allows clients to request exactly the data they need and nothing more.
Comprehensive Answer:
A query language for APIs that allows clients to request exactly the data they need and nothing more.
Difference between GraphQL and REST?
ExperienceREST has multiple endpoints and can suffer from over-fetching/under-fetching. GraphQL has a single endpoint and flexible queries.
Comprehensive Answer:
REST has multiple endpoints and can suffer from over-fetching/under-fetching. GraphQL has a single endpoint and flexible queries.
How to implement 'pagination' correctly?
ExperienceUsing 'offset-based' or 'cursor-based' (preferred for large data) pagination to limit result sizes.
Comprehensive Answer:
Using 'offset-based' or 'cursor-based' (preferred for large data) pagination to limit result sizes.
Explain 'Bull' or 'Bee-Queue'.
ExperienceRedis-based message queue libraries used for handling background jobs and asynchronous tasks in Node.js.
Comprehensive Answer:
Redis-based message queue libraries used for handling background jobs and asynchronous tasks in Node.js.
How to use 'child_process' module?
ExperienceProvides the ability to spawn child processes using `spawn`, `fork`, `exec`, or `execFile`.
Comprehensive Answer:
Provides the ability to spawn child processes using `spawn`, `fork`, `exec`, or `execFile`.
Difference between `spawn` and `exec`?
Experience`spawn` returns a stream (better for large data). `exec` buffers the entire output in memory (simpler but limited to a few MBs).
Comprehensive Answer:
`spawn` returns a stream (better for large data). `exec` buffers the entire output in memory (simpler but limited to a few MBs).
What is 'N-API'?
ExperienceA stable API for building native Node.js addons that is independent of the underlying JavaScript engine version.
Comprehensive Answer:
A stable API for building native Node.js addons that is independent of the underlying JavaScript engine version.
How to handle 'unhandledRejection' and 'uncaughtException'?
ExperienceBy adding listeners to the `process` object to log the error and crash/restart gracefully.
Comprehensive Answer:
By adding listeners to the `process` object to log the error and crash/restart gracefully.
Explain 'Dependency Injection' (DI).
ExperienceA design pattern where an object receives its dependencies from the outside rather than creating them itself, improving testability.
Comprehensive Answer:
A design pattern where an object receives its dependencies from the outside rather than creating them itself, improving testability.
What is 'Inversion of Control' (IoC)?
ExperienceA principle where the control of object creation and lifecycle is shifted from the programmer to a framework/container.
Comprehensive Answer:
A principle where the control of object creation and lifecycle is shifted from the programmer to a framework/container.
How to implement 'Rate Limiting'?
ExperienceUsing `express-rate-limit` or a custom Redis-based store to track and limit requests per IP.
Comprehensive Answer:
Using `express-rate-limit` or a custom Redis-based store to track and limit requests per IP.
What is 'Log Rotation'?
ExperienceThe practice of periodically archiving and deleting old log files to prevent them from consuming too much disk space.
Comprehensive Answer:
The practice of periodically archiving and deleting old log files to prevent them from consuming too much disk space.
Explain 'Winston' or 'Pino'.
ExperiencePowerful logging libraries for Node.js that support different log levels and transports (file, console, external services).
Comprehensive Answer:
Powerful logging libraries for Node.js that support different log levels and transports (file, console, external services).
How to handle database migrations?
ExperienceUsing tools like `knex` or `sequelize-cli` to track and apply changes to the database schema over time.
Comprehensive Answer:
Using tools like `knex` or `sequelize-cli` to track and apply changes to the database schema over time.
What is 'Circuit Breaker' pattern?
ExperienceA design pattern used to prevent an application from repeatedly trying to execute an operation that's likely to fail (e.g., calling a down service).
Comprehensive Answer:
A design pattern used to prevent an application from repeatedly trying to execute an operation that's likely to fail (e.g., calling a down service).
Explain V8 Engine Pipeline.
AdvancedIgnition (interpreter) generates bytecode -> TurboFan (compiler) optimizes hot code to machine code -> Orinoco (GC) reclaims memory.
Comprehensive Answer:
Ignition (interpreter) generates bytecode -> TurboFan (compiler) optimizes hot code to machine code -> Orinoco (GC) reclaims memory.
What is 'Hidden Classes' in V8?
AdvancedAn optimization technique where V8 creates internal classes for objects with the same structure to allow fast property access.
Comprehensive Answer:
An optimization technique where V8 creates internal classes for objects with the same structure to allow fast property access.
Explain 'Inlining' optimization.
AdvancedV8 replaces a function call with the actual body of the function to reduce call overhead if the function is small and frequently called.
Comprehensive Answer:
V8 replaces a function call with the actual body of the function to reduce call overhead if the function is small and frequently called.
What is 'Buffer.alloc' vs 'Buffer.allocUnsafe'?
Advanced`alloc` zeroes the memory (safe). `allocUnsafe` does not zero memory (faster but may contain old sensitive data).
Comprehensive Answer:
`alloc` zeroes the memory (safe). `allocUnsafe` does not zero memory (faster but may contain old sensitive data).
Explain 'Zero-copy' in Node.js.
AdvancedA technique to avoid unnecessary data copying between the kernel and application memory, often used in networking and file transfers.
Comprehensive Answer:
A technique to avoid unnecessary data copying between the kernel and application memory, often used in networking and file transfers.
What is 'V8 Heap Snapshot'?
AdvancedA file representing the memory distribution of a Node.js process at a specific point in time, used for memory leak analysis.
Comprehensive Answer:
A file representing the memory distribution of a Node.js process at a specific point in time, used for memory leak analysis.
Explain 'Flame Graphs'.
AdvancedA visualization tool used to analyze CPU profile data and find performance bottlenecks in your code.
Comprehensive Answer:
A visualization tool used to analyze CPU profile data and find performance bottlenecks in your code.
Deep Dive: libuv thread pool size.
AdvancedDefaults to 4. Can be increased via `UV_THREADPOOL_SIZE` for handling more simultaneous file/crypto/dns operations.
Comprehensive Answer:
Defaults to 4. Can be increased via `UV_THREADPOOL_SIZE` for handling more simultaneous file/crypto/dns operations.
What is 'Isolate' in V8?
AdvancedAn Isolate is an independent instance of the V8 engine, including its own heap, garbage collector, etc.
Comprehensive Answer:
An Isolate is an independent instance of the V8 engine, including its own heap, garbage collector, etc.
Explain 'Crankshaft' (Legacy) vs 'TurboFan'.
AdvancedCrankshaft was the old JIT compiler. TurboFan is the modern replacement that handles ES6 features and optimization more effectively.
Comprehensive Answer:
Crankshaft was the old JIT compiler. TurboFan is the modern replacement that handles ES6 features and optimization more effectively.
How to write Native Addons with C++?
AdvancedUsing N-API or NaN (Native Abstractions for Node.js) to bridge C++ code and the V8 engine.
Comprehensive Answer:
Using N-API or NaN (Native Abstractions for Node.js) to bridge C++ code and the V8 engine.
Explain 'SharedArrayBuffer' and 'Atomics'.
AdvancedAllow multiple threads (Workers) to share the same memory and perform atomic operations to avoid race conditions.
Comprehensive Answer:
Allow multiple threads (Workers) to share the same memory and perform atomic operations to avoid race conditions.
Deep Dive: 'Tick' process in Node.js.
AdvancedA single iteration of the event loop. The number of ticks per second is a metric of loop latency.
Comprehensive Answer:
A single iteration of the event loop. The number of ticks per second is a metric of loop latency.
What is 'Event Loop Lag'?
AdvancedThe delay between when an event is scheduled and when it's actually processed. High lag indicates a blocked event loop.
Comprehensive Answer:
The delay between when an event is scheduled and when it's actually processed. High lag indicates a blocked event loop.
How to implement Custom Streams?
AdvancedBy extending the `Readable`, `Writable`, or `Transform` classes and implementing the `_read`, `_write`, or `_transform` methods.
Comprehensive Answer:
By extending the `Readable`, `Writable`, or `Transform` classes and implementing the `_read`, `_write`, or `_transform` methods.
Explain 'QUIC' and 'HTTP/3' support.
AdvancedNewer protocols that reduce latency by using UDP instead of TCP, with built-in encryption and multiplexing.
Comprehensive Answer:
Newer protocols that reduce latency by using UDP instead of TCP, with built-in encryption and multiplexing.
How to handle 'BigInt' in Node.js?
AdvancedUsing the `BigInt` type (e.g., `100n`) for handling integers larger than `Number.MAX_SAFE_INTEGER`.
Comprehensive Answer:
Using the `BigInt` type (e.g., `100n`) for handling integers larger than `Number.MAX_SAFE_INTEGER`.
Explain 'Shadow DOM' vs 'Virtual DOM'.
AdvancedShadow DOM is a browser technology for encapsulation. Virtual DOM is a JavaScript library concept for UI syncing.
Comprehensive Answer:
Shadow DOM is a browser technology for encapsulation. Virtual DOM is a JavaScript library concept for UI syncing.
What is 'Tree Shaking' in Node.js production?
AdvancedRemoving unused code from the final bundle during the build step using tools like Webpack or Rollup.
Comprehensive Answer:
Removing unused code from the final bundle during the build step using tools like Webpack or Rollup.
Security: 'ReDoS' (Regular Expression Denial of Service).
AdvancedAn attack that exploits poorly written Regex that take exponential time to process certain strings, blocking the event loop.
Comprehensive Answer:
An attack that exploits poorly written Regex that take exponential time to process certain strings, blocking the event loop.
How to implement 'Observability'?
AdvancedCombining Metrics (Prometheus), Logs (ELK), and Traces (Tempo) to understand the internal state of the system.
Comprehensive Answer:
Combining Metrics (Prometheus), Logs (ELK), and Traces (Tempo) to understand the internal state of the system.
Explain 'Chaos Engineering' in Node.js.
AdvancedPurposely introducing failures (like killing nodes or adding latency) to test the resilience of the system.
Comprehensive Answer:
Purposely introducing failures (like killing nodes or adding latency) to test the resilience of the system.
Deep Dive: `require()` cache.
AdvancedModules are cached after the first time they are loaded. Subsequent requires return the same instance, making them effective singletons.
Comprehensive Answer:
Modules are cached after the first time they are loaded. Subsequent requires return the same instance, making them effective singletons.
Explain 'Circular Dependencies' in Node.js.
AdvancedOccurs when Module A requires Module B, and B requires A. Node.js handles this by returning an incomplete export object from the second require.
Comprehensive Answer:
Occurs when Module A requires Module B, and B requires A. Node.js handles this by returning an incomplete export object from the second require.
How to use 'Inspector' module?
AdvancedAllows you to programmatically interact with the V8 inspector for debugging and profiling.
Comprehensive Answer:
Allows you to programmatically interact with the V8 inspector for debugging and profiling.
Explain 'Native Messaging' in Chrome Extensions via Node.
AdvancedA way for a browser extension to exchange messages with a native Node.js application installed on the user's machine.
Comprehensive Answer:
A way for a browser extension to exchange messages with a native Node.js application installed on the user's machine.
What is 'JIT' (Just In Time) Compilation?
AdvancedA method of improving performance of interpreted programs by compiling code into machine language at runtime.
Comprehensive Answer:
A method of improving performance of interpreted programs by compiling code into machine language at runtime.
How to implement 'Multi-tenant' architecture?
AdvancedUsing separate databases per tenant, separate schemas, or a discriminator column in shared tables.
Comprehensive Answer:
Using separate databases per tenant, separate schemas, or a discriminator column in shared tables.
Explain 'Atomic' commits with MongoDB/Node.
AdvancedUsing 'Transactions' (since Mongo 4.0) to ensure multiple operations either all succeed or all fail.
Comprehensive Answer:
Using 'Transactions' (since Mongo 4.0) to ensure multiple operations either all succeed or all fail.
How to handle 'Thundering Herd' problem?
AdvancedUsing 'Coalescing' (e.g., via `dataloader`) to ensure that multiple identical requests for the same resource only trigger one DB/API call.
Comprehensive Answer:
Using 'Coalescing' (e.g., via `dataloader`) to ensure that multiple identical requests for the same resource only trigger one DB/API call.
What is 'Symlink' in Node.js modules?
AdvancedA symbolic link to a file or directory. Node.js resolves these differently depending on the `--preserve-symlinks` flag.
Comprehensive Answer:
A symbolic link to a file or directory. Node.js resolves these differently depending on the `--preserve-symlinks` flag.
Explain 'Module Wrapper' in Node.js.
AdvancedNode.js wraps every module in a function: `(function(exports, require, module, __filename, __dirname) { ... })` before executing it.
Comprehensive Answer:
Node.js wraps every module in a function: `(function(exports, require, module, __filename, __dirname) { ... })` before executing it.
Difference between `exports` and `module.exports`?
Advanced`exports` is a reference to `module.exports`. If you assign a new value to `exports`, it no longer references `module.exports`, causing no exports.
Comprehensive Answer:
`exports` is a reference to `module.exports`. If you assign a new value to `exports`, it no longer references `module.exports`, causing no exports.
How to handle 'Zlib' for compression?
AdvancedUsing the `zlib` module to compress/decompress buffers and streams using Gzip, Deflate, or Brotli.
Comprehensive Answer:
Using the `zlib` module to compress/decompress buffers and streams using Gzip, Deflate, or Brotli.
Explain 'Pre-parsing' in V8.
AdvancedV8 lazily parses functions only when they are needed, performing a quick 'pre-parse' first to check for syntax errors.
Comprehensive Answer:
V8 lazily parses functions only when they are needed, performing a quick 'pre-parse' first to check for syntax errors.
What is 'Code Cache'?
AdvancedV8 caches the generated bytecode for scripts to speed up subsequent loads of the same script.
Comprehensive Answer:
V8 caches the generated bytecode for scripts to speed up subsequent loads of the same script.
How to build 'CLI' tools with Node.js?
AdvancedUsing libraries like `commander`, `yargs`, or `inquirer` and adding `#!/usr/bin/env node` to the main file.
Comprehensive Answer:
Using libraries like `commander`, `yargs`, or `inquirer` and adding `#!/usr/bin/env node` to the main file.
Explain 'TTY' module.
AdvancedUsed to interact with terminal windows (e.g., checking if the app is running in a terminal via `process.stdout.isTTY`).
Comprehensive Answer:
Used to interact with terminal windows (e.g., checking if the app is running in a terminal via `process.stdout.isTTY`).
What is 'Vm' module?
AdvancedAllows compiling and running code within V8 Virtual Machine contexts. Not a security sandbox!
Comprehensive Answer:
Allows compiling and running code within V8 Virtual Machine contexts. Not a security sandbox!
How to implement 'A/B Testing' server-side?
AdvancedAssigning users to groups based on their ID hash and serving different logic/routes accordingly.
Comprehensive Answer:
Assigning users to groups based on their ID hash and serving different logic/routes accordingly.
Explain 'Service Discovery' in Microservices.
AdvancedHow services find each other's locations (IP/Port) in a dynamic network, using tools like Consul or Kubernetes DNS.
Comprehensive Answer:
How services find each other's locations (IP/Port) in a dynamic network, using tools like Consul or Kubernetes DNS.
What is 'API Gateway' pattern?
AdvancedA single entry point for all clients that routes requests to internal microservices, handles auth, and optionally aggregates data.
Comprehensive Answer:
A single entry point for all clients that routes requests to internal microservices, handles auth, and optionally aggregates data.
Explain 'Sidecar' pattern.
AdvancedDeploying a helper service (like a proxy or logger) alongside the main application container.
Comprehensive Answer:
Deploying a helper service (like a proxy or logger) alongside the main application container.
How to handle 'Semantic Versioning' (SemVer)?
AdvancedFollowing the `MAJOR.MINOR.PATCH` format to communicate breaking changes, features, and bug fixes.
Comprehensive Answer:
Following the `MAJOR.MINOR.PATCH` format to communicate breaking changes, features, and bug fixes.
What is 'NPM Audit'?
AdvancedA command that checks for known security vulnerabilities in your project's dependencies.
Comprehensive Answer:
A command that checks for known security vulnerabilities in your project's dependencies.
Explain 'Peer Dependencies'.
AdvancedDependencies that a package requires the HOST application to provide, common in plugin development.
Comprehensive Answer:
Dependencies that a package requires the HOST application to provide, common in plugin development.
How to use 'AbortSignal' across multiple async tasks?
AdvancedPassing the same `signal` to multiple fetch/timer calls so they all cancel when the `controller.abort()` is called.
Comprehensive Answer:
Passing the same `signal` to multiple fetch/timer calls so they all cancel when the `controller.abort()` is called.
What is 'Top-level Await'?
AdvancedSupport for using `await` at the top level of ES modules without being inside an `async` function.
Comprehensive Answer:
Support for using `await` at the top level of ES modules without being inside an `async` function.
Explain 'WebAssembly' (Wasm) with Node.js.
AdvancedLoading and running high-performance binary code (compiled from C++/Rust) inside the Node.js runtime.
Comprehensive Answer:
Loading and running high-performance binary code (compiled from C++/Rust) inside the Node.js runtime.
How to implement 'Data Masking' for PII?
AdvancedObfuscating sensitive information (like Credit Card numbers) before logging or displaying it to unauthorized users.
Comprehensive Answer:
Obfuscating sensitive information (like Credit Card numbers) before logging or displaying it to unauthorized users.
Read a file and count words.
BeginnerUse fs.readFile or streams.
Comprehensive Answer:
Use fs.readFile or streams.
Code Snippet:
const fs = require('fs');
fs.readFile('test.txt', 'utf8', (err, data) => {
const words = data.split(/\s+/).length;
console.log(words);
});Create a basic HTTP server.
BeginnerUse the http module.
Comprehensive Answer:
Use the http module.
Code Snippet:
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello Node!');
}).listen(3000);Get all files in a directory.
BeginnerUse fs.readdir.
Comprehensive Answer:
Use fs.readdir.
Code Snippet:
const fs = require('fs');
fs.readdir('./', (err, files) => {
console.log(files);
});Convert callback-based fs.readFile to Promise.
ExperienceManual promise or util.promisify.
Comprehensive Answer:
Manual promise or util.promisify.
Code Snippet:
const fs = require('fs').promises;
async function read() {
const data = await fs.readFile('f.txt', 'utf8');
return data;
}Implement a simple EventEmitter.
ExperienceCreate a custom class extender.
Comprehensive Answer:
Create a custom class extender.
Code Snippet:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('test', () => console.log('OK'));
myEmitter.emit('test');How to parse JSON from body in vanilla Node?
ExperienceAccumulate chunks of data.
Comprehensive Answer:
Accumulate chunks of data.
Code Snippet:
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const data = JSON.parse(body);
});Implement basic authentication middleware in Express.
ExperienceCheck headers for auth token.
Comprehensive Answer:
Check headers for auth token.
Code Snippet:
const auth = (req, res, next) => {
if(req.headers.auth === 'secret') next();
else res.status(401).send();
};Calculate file hash (SHA-256).
ExperienceUse crypto module and streams.
Comprehensive Answer:
Use crypto module and streams.
Code Snippet:
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
stream.on('data', data => hash.update(data));Pipe a file to response (download).
BeginnerCreate readable stream and pipe to res.
Comprehensive Answer:
Create readable stream and pipe to res.
Code Snippet:
fs.createReadStream('file.pdf').pipe(res);Merge two objects in JS.
BeginnerSpread operator or Object.assign.
Comprehensive Answer:
Spread operator or Object.assign.
Code Snippet:
const merged = { ...obj1, ...obj2 };Check if a path is a directory or file.
BeginnerUse fs.stat and .isDirectory().
Comprehensive Answer:
Use fs.stat and .isDirectory().
Code Snippet:
fs.stat('path', (err, stats) => {
console.log(stats.isDirectory());
});How to run multiple promises in parallel?
ExperienceUse Promise.all().
Comprehensive Answer:
Use Promise.all().
Code Snippet:
await Promise.all([task1(), task2()]);Implement a Delay function.
BeginnerReturn a promise that resolves after N ms.
Comprehensive Answer:
Return a promise that resolves after N ms.
Code Snippet:
const delay = ms => new Promise(res => setTimeout(res, ms));Find unique values in array.
BeginnerUse Set.
Comprehensive Answer:
Use Set.
Code Snippet:
const unique = [...new Set(arr)];Get current platform and CPU count.
BeginnerUse os module.
Comprehensive Answer:
Use os module.
Code Snippet:
const os = require('os');
console.log(os.platform(), os.cpus().length);Zip a file using zlib.
ExperiencePipe read stream -> createGzip -> write stream.
Comprehensive Answer:
Pipe read stream -> createGzip -> write stream.
Code Snippet:
fs.createReadStream('file.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('file.txt.gz'));How to catch unhandled promise rejections?
Experienceprocess listener.
Comprehensive Answer:
process listener.
Code Snippet:
process.on('unhandledRejection', (err) => {
console.error(err);
});Implement a basic Cluster worker logic.
ExperienceCheck cluster.isMaster and fork.
Comprehensive Answer:
Check cluster.isMaster and fork.
Code Snippet:
if (cluster.isPrimary) cluster.fork();
else http.createServer(...).listen(80);Filter an array of objects by property.
BeginnerArray.filter.
Comprehensive Answer:
Array.filter.
Code Snippet:
const users = list.filter(u => u.age > 18);Format currency in JS.
BeginnerIntl.NumberFormat.
Comprehensive Answer:
Intl.NumberFormat.
Code Snippet:
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(100);Generate a random token string.
ExperienceUse crypto.randomBytes.
Comprehensive Answer:
Use crypto.randomBytes.
Code Snippet:
crypto.randomBytes(32).toString('hex');Check if a variable is an array.
BeginnerArray.isArray().
Comprehensive Answer:
Array.isArray().
Code Snippet:
Array.isArray(myVar);Implement a simple LRU cache (Logic).
AdvancedUse a Map to track usage order.
Comprehensive Answer:
Use a Map to track usage order.
Code Snippet:
cache.delete(key); cache.set(key, value);How to handle timeouts in Fetch?
ExperienceAbortController with setTimeout.
Comprehensive Answer:
AbortController with setTimeout.
Code Snippet:
setTimeout(() => controller.abort(), 5000);Convert string to base64.
BeginnerBuffer.from().toString('base64').
Comprehensive Answer:
Buffer.from().toString('base64').
Code Snippet:
Buffer.from('hello').toString('base64');Group array of objects by a key.
ExperienceReduce into an object.
Comprehensive Answer:
Reduce into an object.
Code Snippet:
arr.reduce((acc, obj) => {
(acc[obj.key] = acc[obj.key] || []).push(obj);
return acc;
}, {});How to execute a shell command?
Beginnerchild_process.exec.
Comprehensive Answer:
child_process.exec.
Code Snippet:
exec('ls', (err, stdout) => console.log(stdout));Check if a string is a valid JSON.
BeginnerTry-catch JSON.parse.
Comprehensive Answer:
Try-catch JSON.parse.
Code Snippet:
try { JSON.parse(str); return true; } catch { return false; }Implement a custom Writable stream.
AdvancedImplement _write method.
Comprehensive Answer:
Implement _write method.
Code Snippet:
class MyW extends Writable {
_write(chunk, enc, next) { ... next(); }
}Find the intersection of two arrays.
BeginnerFilter and Includes.
Comprehensive Answer:
Filter and Includes.
Code Snippet:
arr1.filter(x => arr2.includes(x));How to detect a memory leak in a simple loop?
AdvancedContinuously add items to a global array.
Comprehensive Answer:
Continuously add items to a global array.
Code Snippet:
setInterval(() => leaks.push(new Array(100000)), 100);Debounce a function (Generic).
ExperienceTimeout closure.
Comprehensive Answer:
Timeout closure.
Code Snippet:
return (...args) => {
clearTimeout(t);
t = setTimeout(() => f(...args), ms);
};Throttle a function (Generic).
ExperienceFlag based execution.
Comprehensive Answer:
Flag based execution.
Code Snippet:
if(!wait) { f(); wait = true; setTimeout(()=>wait=false, ms); }Deep clone an object (using structuredClone).
BeginnerNative modern JS method.
Comprehensive Answer:
Native modern JS method.
Code Snippet:
const copy = structuredClone(original);Implement a queue using two stacks.
AdvancedPush to S1, Pop from S2 (filling from S1 when empty).
Comprehensive Answer:
Push to S1, Pop from S2 (filling from S1 when empty).
Code Snippet:
enqueue(x) { s1.push(x) }Check for prime numbers.
BeginnerStandard math loop.
Comprehensive Answer:
Standard math loop.
Code Snippet:
for(let i=2; i < n; i++) if(n%i===0) return false;Reverse words in a sentence.
BeginnerSplit, reverse, join.
Comprehensive Answer:
Split, reverse, join.
Code Snippet:
s.split(' ').reverse().join(' ');Find the median of an array.
ExperienceSort and pick middle.
Comprehensive Answer:
Sort and pick middle.
Code Snippet:
const s = arr.sort((a,b)=>a-b); return s[len/2];Convert epoch to human readable date.
Beginnernew Date(ms).
Comprehensive Answer:
new Date(ms).
Code Snippet:
new Date(1600000000 * 1000).toLocaleString();Implement a retry logic for fetch.
ExperienceLoop with try-catch and delay.
Comprehensive Answer:
Loop with try-catch and delay.
Code Snippet:
for(let i=0; i<3; i++) try { return fetch(); } catch { await delay(); }Flatten nested JSON.
AdvancedRecursive key concatenation.
Comprehensive Answer:
Recursive key concatenation.
Code Snippet:
const flat = (o, p) => ... o[p + key] = val;How to get query params from URL in Node?
BeginnerUse url module or URL class.
Comprehensive Answer:
Use url module or URL class.
Code Snippet:
const params = new URL(req.url, 'http://x').searchParams;Capitalize first letter of string.
BeginnerSlice and toUpperCase.
Comprehensive Answer:
Slice and toUpperCase.
Code Snippet:
s[0].toUpperCase() + s.slice(1);Count occurrences of characters in string.
BeginnerReduce into object.
Comprehensive Answer:
Reduce into object.
Code Snippet:
s.split('').reduce((a,c) => { a[c] = (a[c]||0)+1; return a; }, {});Write a stream-based file copy function.
BeginnerPipe read to write stream.
Comprehensive Answer:
Pipe read to write stream.
Code Snippet:
fs.createReadStream('a').pipe(fs.createWriteStream('b'));Find the first non-repeating character.
ExperienceFrequency count and find index.
Comprehensive Answer:
Frequency count and find index.
Code Snippet:
const char = s.split('').find(c => s.indexOf(c) === s.lastIndexOf(c));Implement Binary Search.
ExperienceMidpoint comparison in sorted array.
Comprehensive Answer:
Midpoint comparison in sorted array.
Code Snippet:
while(l <= r) { m = (l+r)/2; if(arr[m] === t) ... }How to use worker threads for heavy math?
AdvancedSpawn worker and listen for message.
Comprehensive Answer:
Spawn worker and listen for message.
Code Snippet:
const worker = new Worker('./math.js'); worker.postMessage(n);Implement a simple string template engine.
ExperienceRegex replace with object keys.
Comprehensive Answer:
Regex replace with object keys.
Code Snippet:
s.replace(/{{(\w+)}}/g, (m, k) => obj[k]);Check if two strings are anagrams.
BeginnerSort and compare.
Comprehensive Answer:
Sort and compare.
Code Snippet:
sort(s1) === sort(s2);