Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
Short answer: Explain the event loop phases. Node.js uses the event loop to handle async tasks without blocking. Main phases: Timers: Executes callbacks scheduled by setTimeout and setInterval. Pending callbacks: Execute…
Short answer: phases. Node.js uses the event loop to handle async tasks without blocking. Main phases: Timers: Executes callbacks scheduled by setTimeout and setInterval. Pending callbacks: Executes I/O callbacks deferre…
Short answer: Node.js is awesome for I/O-heavy, real-time apps, but it’s not ideal for: CPU-intensive tasks: Heavy computations block the event loop and slow down all requests. Explain a bit more Applications requiring m…
Short answer: Use real environment variables on the server or container. Avoid committing .env files to source control. In cloud providers, set environment variables in the dashboard. Use tools like dotenv only in develo…
Short answer: require('dotenv').config(); console.log(process.env.DB_PASSWORD); require('dotenv').config(); console.log(process.env.DB_PASSWORD); require('dotenv').config(); console.log(process.env.DB_PASSWORD); require(…
Short answer: Avoid directly inserting user input into queries. Use safe query methods (e.g., Mongoose’s query APIs). Validate and sanitize input. For example, don’t allow user input to modify query operators like $gt, $…
Short answer: 📌 Middleware example: function auth(req, res, next) { const token = req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).send('Unauthorized'); try { const user = jwt.verify(token, '…
Short answer: You can use native drivers or ORMs like Sequelize. Example with MySQL native driver: const mysql = require('mysql2/promise'); async function connect() { const connection = await mysql.createConnection({ hos…
Short answer: Worker threads run JavaScript code in parallel threads — useful for CPU-intensive tasks that block the event loop. Use them when your app needs heavy computation without blocking other requests. Real-world…
Short answer: Node.js uses the V8 JavaScript engine’s garbage collector, which: Automatically frees memory that's no longer referenced. Uses a generational GC: young generation (short-lived objects) and old generation (l…
Short answer: sync function connect() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'test' }); const [rows] = await connection.execute('SELECT * FROM users'); console.log(…
Short answer: Worker threads allow you to run JavaScript code in parallel on multiple threads within the same process — useful for CPU-intensive tasks like image processing or complex calculations without blocking the ma…
Short answer: Asynchronous and Event-Driven: Handles multiple requests without blocking. Fast Execution: Powered by the V8 engine. Single-Threaded but Scalable: Uses event loop and callbacks for handling concurrency. Cro…
Short answer: Callbacks: Functions passed as arguments, executed when async operation finishes. Can lead to “callback hell.” Promises: Objects representing future results; allow chaining with .then(). Async/await: Syntac…
Short answer: Docker packages your app and its environment into a container for consistent deployment. Basic steps: Create a Dockerfile: FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install --production COPY .…
Short answer: Never hardcode keys in your source code. Store them in environment variables or secure vaults. Use .env files with .gitignore to avoid committing secrets. Rotate keys regularly. Use scopes/permissions to li…
Short answer: Child processes are separate processes spawned by your Node.js app to run shell commands or other programs, enabling parallel execution. const { exec } = require('child_process'); exec('ls -la', (err, stdou…
Short answer: Feature Node.js Apache Thread Model Single-threaded event loop Multi-threaded I/O Non-blocking Blocking by default Performance Very high for I/O operations Good but resource intensive Use Case Real-time app…
Short answer: V8 engine manages memory automatically with garbage collection. To detect leaks: Use tools like Chrome DevTools, node --inspect, or heapdump. Monitor memory usage over time. Look for increasing memory witho…
Short answer: Use logging libraries like winston or pino for structured logs. Separate logs into levels (info, warn, error). Output logs to files or external services (Logstash, Datadog, Splunk). Implement log rotation t…
Short answer: Use try/catch blocks with async/await to catch exceptions. Handle errors in callbacks or promise .catch() when using promise-based APIs. Log errors for debugging. Return meaningful error messages to the cli…
Short answer: You can access environment variables using process.env. const port = process.env.PORT || 3000; These variables are set outside your app, often in your shell or deployment environment. Real-world example (Sh…
Short answer: Mocking replaces real dependencies with fake versions to isolate the unit you’re testing. Common tools: Sinon: For mocks, spies, and stubs. Proxyquire: Replace dependencies when requiring modules. Jest: Has…
Short answer: pp.js — Use the custom module const math = require('./mathUtils'); console.log(math.add(5, 3)); // Output: 8 console.log(math.subtract(10, 4)); // Output: 6 ✅ This pattern helps you break code into organize…
Short answer: Node.js uses the event loop with phases (timers, I/O callbacks, idle, poll, check, close callbacks) to manage async tasks. Explain a bit more Async queues (e.g., with libraries like async.queue) allow you t…
Node.js Node.js Tutorial · Node.js
Short answer: Explain the event loop phases. Node.js uses the event loop to handle async tasks without blocking. Main phases: Timers: Executes callbacks scheduled by setTimeout and setInterval. Pending callbacks: Executes I/O callbacks deferred to next iteration. Idle, prepare: Internal operations. Poll: Retrieves new I/O events; executes I/O callbacks. Check: Executes callbacks scheduled by setImmediate. Close callbacks: Handles…
closed connections. Tasks are processed in this order each loop iteration.
ShopNest’s Node API handles many checkout requests concurrently because I/O (DB/HTTP) is non-blocking on the event loop.
Node.js Node.js Tutorial · Node.js
Short answer: phases. Node.js uses the event loop to handle async tasks without blocking. Main phases: Timers: Executes callbacks scheduled by setTimeout and setInterval. Pending callbacks: Executes I/O callbacks deferred to next iteration. Idle, prepare: Internal operations. Poll: Retrieves new I/O events; executes I/O callbacks. Check: Executes callbacks… scheduled… by…… setImmediate. Close callbacks: Handles closed…
connections. Tasks are processed in this order each loop iteration.
ShopNest’s Node API handles many checkout requests concurrently because I/O (DB/HTTP) is non-blocking on the event loop.
Node.js Node.js Tutorial · Node.js
Short answer: Node.js is awesome for I/O-heavy, real-time apps, but it’s not ideal for: CPU-intensive tasks: Heavy computations block the event loop and slow down all requests.
Applications requiring multithreaded parallelism: Though worker threads exist, Node.js is not designed for parallel CPU-heavy workloads by default. When you need mature libraries for complex domains: Some domains (like machine learning) have better ecosystems in other languages.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Use real environment variables on the server or container. Avoid committing .env files to source control. In cloud providers, set environment variables in the dashboard. Use tools like dotenv only in development. For sensitive secrets, consider secret managers like AWS Secrets Manager or HashiCorp Vault.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: require('dotenv').config(); console.log(process.env.DB_PASSWORD); require('dotenv').config(); console.log(process.env.DB_PASSWORD); require('dotenv').config(); console.log(process.env.DB_PASSWORD); require('dotenv').config(); console.log(process.env.DB_PASSWORD);
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Avoid directly inserting user input into queries. Use safe query methods (e.g., Mongoose’s query APIs). Validate and sanitize input. For example, don’t allow user input to modify query operators like $gt, $ne.
Node.js Node.js Tutorial · Node.js
Short answer: 📌 Middleware example: function auth(req, res, next) { const token = req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).send('Unauthorized'); try { const user = jwt.verify(token, 'secret'); req.user = user; next(); } catch { res.status(403).send('Invalid token'); } }
📌 Middleware example: function auth(req, res, next) { const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).send('Unauthorized'); try { const user = jwt.verify(token, 'secret');
req.user = user; next(); } catch { res.status(403).send('Invalid token'); }
}
Express middleware authenticates JWT, then the /orders route handler creates the order.
Node.js Node.js Tutorial · Node.js
Short answer: You can use native drivers or ORMs like Sequelize. Example with MySQL native driver: const mysql = require('mysql2/promise'); async function connect() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'test' }); const [rows] = await connection.execute('SELECT * FROM users'); console.log(rows); }
You can use native drivers or ORMs like Sequelize. Example with MySQL native driver: const mysql = require('mysql2/promise');
async function connect() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'test' }); const [rows] = await connection.execute('SELECT * FROM users'); console.log(rows); }
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Worker threads run JavaScript code in parallel threads — useful for CPU-intensive tasks that block the event loop. Use them when your app needs heavy computation without blocking other requests.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Node.js uses the V8 JavaScript engine’s garbage collector, which: Automatically frees memory that's no longer referenced. Uses a generational GC: young generation (short-lived objects) and old generation (long-lived objects). Runs periodically to clean up unused objects. Developers usually don’t control it directly, but can monitor memory and tune via flags if needed.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: sync function connect() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'test' }); const [rows] = await connection.execute('SELECT * FROM users'); console.log(rows); } sync function connect() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root',… database: 'test' }); const [rows]…… = await connection.execute('SELECT * FROM users'); console.
log(rows); } sync function connect() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', database: 'test' }); const [rows] = await connection.execute('SELECT * FROM users'); console.log(rows); } sync function connect() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root',… database: 'test' }); const [rows] = await connection.execute('SELECT * FROM users'); console.log(rows); }
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Worker threads allow you to run JavaScript code in parallel on multiple threads within the same process — useful for CPU-intensive tasks like image processing or complex calculations without blocking the main event loop. const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (msg) => console.log('From worker:', msg)); worker.postMessage('start');
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Asynchronous and Event-Driven: Handles multiple requests without blocking. Fast Execution: Powered by the V8 engine. Single-Threaded but Scalable: Uses event loop and callbacks for handling concurrency. Cross-platform: Runs on Windows, Linux, and macOS. NPM (Node Package Manager): Massive ecosystem of reusable packages.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Callbacks: Functions passed as arguments, executed when async operation finishes. Can lead to “callback hell.” Promises: Objects representing future results; allow chaining with .then(). Async/await: Syntactic sugar over promises; lets you write async code that looks synchronous, improving readability.
ShopNest’s Node API handles many checkout requests concurrently because I/O (DB/HTTP) is non-blocking on the event loop.
Node.js Node.js Tutorial · Node.js
Short answer: Docker packages your app and its environment into a container for consistent deployment. Basic steps: Create a Dockerfile: FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install --production COPY . . CMD ["node", "app.js"] Build and run the container: docker build -t my-node-app . docker run -p 3000:3000 my-node-app
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Never hardcode keys in your source code. Store them in environment variables or secure vaults. Use .env files with .gitignore to avoid committing secrets. Rotate keys regularly. Use scopes/permissions to limit key usage.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Child processes are separate processes spawned by your Node.js app to run shell commands or other programs, enabling parallel execution. const { exec } = require('child_process'); exec('ls -la', (err, stdout, stderr) => { if (err) console.error(err); console.log(stdout); }); Useful for running system commands or scripts without blocking your main app.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Feature Node.js Apache Thread Model Single-threaded event loop Multi-threaded I/O Non-blocking Blocking by default Performance Very high for I/O operations Good but resource intensive Use Case Real-time apps, APIs Websites, PHP apps 📌 Example: For a chat application or API server with thousands of concurrent users, Node.js performs better than Apache.
Node.js Node.js Tutorial · Node.js
Short answer: V8 engine manages memory automatically with garbage collection. To detect leaks: Use tools like Chrome DevTools, node --inspect, or heapdump. Monitor memory usage over time. Look for increasing memory without release, which signals leaks. Modules & Package Management
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Use logging libraries like winston or pino for structured logs. Separate logs into levels (info, warn, error). Output logs to files or external services (Logstash, Datadog, Splunk). Implement log rotation to prevent disk space issues. Make logs easy to search and analyze.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Use try/catch blocks with async/await to catch exceptions. Handle errors in callbacks or promise .catch() when using promise-based APIs. Log errors for debugging. Return meaningful error messages to the client without exposing sensitive info. Example: try { const user = await User.findById(id);
if (!user) throw new Error('User not found'); } catch (error) { console.error(error); res.status(500).send('Something went wrong'); }
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: You can access environment variables using process.env. const port = process.env.PORT || 3000; These variables are set outside your app, often in your shell or deployment environment.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Mocking replaces real dependencies with fake versions to isolate the unit you’re testing. Common tools: Sinon: For mocks, spies, and stubs. Proxyquire: Replace dependencies when requiring modules. Jest: Has built-in mocking capabilities. Example with Sinon: const sinon = require('sinon');
const myModule = require('../myModule');
const dependency = require('../dependency'); describe('test with mock', () => { it('should call dependency once', () => { const stub = sinon.stub(dependency, 'someMethod').returns(42);
const result = myModule.doSomething(); sinon.assert.calledOnce(stub); stub.restore(); }); });
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: pp.js — Use the custom module const math = require('./mathUtils'); console.log(math.add(5, 3)); // Output: 8 console.log(math.subtract(10, 4)); // Output: 6 ✅ This pattern helps you break code into organized, testable, and reusable pieces — just like using built-in or third-party libraries.
dvanced Node.js Concepts pp.js — Use the custom module const math = require('./mathUtils'); console.log(math.add(5, 3)); // Output: 8 console.log(math.subtract(10, 4)); // Output: 6 ✅ This pattern helps you break code into organized, testable, and reusable pieces — just like using built-in or third-party libraries.
A ShopNest BFF in Node.js aggregates catalog and price APIs for the React storefront.
Node.js Node.js Tutorial · Node.js
Short answer: Node.js uses the event loop with phases (timers, I/O callbacks, idle, poll, check, close callbacks) to manage async tasks.
Async queues (e.g., with libraries like async.queue) allow you to: Control concurrency (limit how many async tasks run simultaneously). Queue tasks and process them in order. Example with async library: const async = require('async'); const queue = async.queue(async (task) => { await doWork(task); }, 2); // concurrency = 2 queue.push({ id: 1 }); queue.push({ id: 2 }); Node.js internally uses libuv’s thread pool for async I/O, but the event loop manages task scheduling on the single main thread. Additional Important Node.js Questions & Answers Core Concepts & Runtime