Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
process.nextTick() queues a callback to be invoked immediately after the current operation completes, before the event loop continues. setImmediate() queues a callback to run on the next iteration of the event loop. Exam…
If an error (exception) is thrown but not caught, Node.js will: Print the error stack trace to the console. Immediately terminate the process to avoid unpredictable behavior. Why? Because an uncaught exception might leav…
Injection attacks (SQL, NoSQL) Cross-Site Scripting (XSS) Cross-Site Request Forgery (CSRF) Broken authentication and session management Insecure handling of sensitive data (passwords, API keys) Unvalidated input data Ex…
s expected. Basic example using Mocha and Chai: // calculator.js function add(a, b) { return a + b; } module.exports = add; // test/calculator.test.js const add = require('../calculator'); const { expect } = require('cha…
Node.js uses a single-threaded event loop to handle concurrency. This design: Simplifies programming by avoiding thread-related bugs like race conditions. Uses non-blocking I/O so a single thread can handle many connecti…
Always use parameterized queries or prepared statements instead of string concatenation. Example with MySQL: connection.query('SELECT * FROM users WHERE id = ?', [userId], callback); Use ORM libraries like Sequelize whic…
Answer: Mocha: Flexible test runner, widely used. Jest: Full-featured, zero-config, includes mocks and coverage. Jasmine: Behavior-driven development framework. AVA: Minimalistic and fast. Tape: Simple and small footprin…
Use clustering or process managers like PM2 to utilize multiple CPU cores. Implement caching (in-memory or distributed caches like Redis). Use asynchronous I/O properly (avoid blocking the event loop). Optimize database…
Node.js operates on a single-threaded, event-driven architecture. It uses the event loop to handle multiple connections concurrently, which means it can perform non-blocking I/O operations efficiently. 📌 Real-life analo…
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 iter…
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…
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 sen…
require('dotenv').config(); console.log(process.env.DB_PASSWORD); What interviewers expect A clear definition tied to Node.js in Node.js projects Trade-offs (performance, maintainability, security, cost) When you would a…
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. Wh…
📌 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.…
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. What interviewers…
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 obje…
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);…
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.…
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: R…
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…
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"…
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 ke…
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) =&g…
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 Websit…
Node.js Node.js Tutorial · Node.js
current operation completes, before the event loop continues.
Example:
process.nextTick(() => console.log('nextTick'));
setImmediate(() => console.log('setImmediate'));
console.log('sync');
Output:
sync
nextTick
setImmediate
nextTick runs before any I/O or timers; setImmediate runs after I/O callbacks.
Node.js Node.js Tutorial · Node.js
If an error (exception) is thrown but not caught, Node.js will:
Why? Because an uncaught exception might leave the app in an inconsistent state.
Best practice: Use try/catch for synchronous code, and listen to
'uncaughtException' or 'unhandledRejection' events to log errors and gracefully
shut down:
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1); // Exit to avoid unstable state
});
Node.js Node.js Tutorial · Node.js
Node.js Node.js Tutorial · Node.js
s expected.
Basic example using Mocha and Chai:
// calculator.js
function add(a, b) {
return a + b;
}
module.exports = add;
// test/calculator.test.js
const add = require('../calculator');
const { expect } = require('chai');
describe('add function', () => {
it('should return the sum of two numbers', () => {
const result = add(2, 3);
expect(result).to.equal(5);
});
});
Run tests with:
mocha
This test suite checks if add(2,3) equals 5 — simple and effective.
Node.js Node.js Tutorial · Node.js
Node.js uses a single-threaded event loop to handle concurrency. This design:
thread pool.
So, Node.js can handle many tasks concurrently without spawning multiple OS threads for
each.
Node.js Node.js Tutorial · Node.js
concatenation.
Example with MySQL:
connection.query('SELECT * FROM users WHERE id = ?', [userId],
callback);
Node.js Node.js Tutorial · Node.js
Answer: Mocha: Flexible test runner, widely used. Jest: Full-featured, zero-config, includes mocks and coverage. Jasmine: Behavior-driven development framework. AVA: Minimalistic and fast. Tape: Simple and small footprint.
In a production Node.js application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
Node.js Node.js Tutorial · Node.js
Node.js Node.js Tutorial · Node.js
Node.js operates on a single-threaded, event-driven architecture. It uses the event loop
to handle multiple connections concurrently, which means it can perform non-blocking I/O
operations efficiently.
📌 Real-life analogy:
Think of it like a chef (Node.js) who takes multiple orders (requests) but doesn't cook each
dish one at a time. Instead, they prep and send off tasks (e.g., grilling, baking) and move on
to the next customer while waiting.
Node.js Node.js Tutorial · Node.js
phases.
Node.js uses the event loop to handle async tasks without blocking.
Main phases:
Tasks are processed in this order each loop iteration.
Node.js Node.js Tutorial · Node.js
Node.js is awesome for I/O-heavy, real-time apps, but it’s not ideal for:
requests.
Node.js is not designed for parallel CPU-heavy workloads by default.
machine learning) have better ecosystems in other languages.
Node.js Node.js Tutorial · Node.js
HashiCorp Vault.
Node.js Node.js Tutorial · Node.js
require('dotenv').config(); console.log(process.env.DB_PASSWORD);
In a production Node.js application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
Node.js Node.js Tutorial · Node.js
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.
In a production Node.js application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
Node.js Node.js Tutorial · Node.js
📌 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');
}
}Node.js Node.js Tutorial · Node.js
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.
In a production Node.js application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
Node.js Node.js Tutorial · Node.js
Node.js uses the V8 JavaScript engine’s garbage collector, which:
(long-lived objects).
if needed.Node.js Node.js Tutorial · Node.js
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); }
In a production Node.js application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
Node.js Node.js Tutorial · Node.js
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');
Node.js Node.js Tutorial · Node.js
concurrency.
Node.js Node.js Tutorial · Node.js
finishes. Can lead to “callback hell.”
synchronous, improving readability.
Node.js Node.js Tutorial · Node.js
Docker packages your app and its environment into a container for consistent deployment.
Basic steps:
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
CMD ["node", "app.js"]
docker build -t my-node-app .
docker run -p 3000:3000 my-node-app
Node.js Node.js Tutorial · Node.js
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.
In a production Node.js application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
Node.js Node.js Tutorial · Node.js
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.
Node.js Node.js Tutorial · Node.js
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.