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…
sync function connect() { const uri = 'mongodb://localhost:27017/mydatabase'; const client = new MongoClient(uri); try { wait client.connect(); console.log('Connected to MongoDB'); const db = client.db('mydatabase'); //…
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…
time per process. Clustering allows you to create multiple Node.js processes (workers) that share the same server port. This way, your app can utilize multiple CPU cores and handle more requests concurrently. 📌 Example:…
Node.js is an open-source, cross-platform runtime environment that allows you to run JavaScript on the server side. It’s built on the V8 JavaScript engine developed by Google (the same one used in Chrome). With Node.js,…
EventEmitter allows objects to emit named events and listen for them. Example: const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('greet', (name) => { console.log(`Hello, ${name}!`)…
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…
Process management means keeping your app running reliably, restarting it if it crashes, and managing multiple instances. PM2 is a popular Node.js process manager that: Restarts apps on crashes or code changes Manages cl…
Mongoose is an ODM (Object Data Modeling) library for MongoDB in Node.js. It provides: Schema-based data modeling Validation Middleware (hooks) Easy querying and relationship management You define schemas and models to i…
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…
ge: Number, createdAt: { type: Date, default: Date.now } }); const User = mongoose.model('User', userSchema); // Usage example sync function createUser() { const user = new User({ name: 'Alice', email: 'alice@example.com…
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…
Answer: nd allows async testing. It does not provide assertions, so it’s often paired with assertion libraries like Chai. What interviewers expect A clear definition tied to Node.js in Node.js projects Trade-offs (perfor…
PM2 is a popular production process manager for Node.js applications. It helps you: Manage and keep apps alive forever (auto-restart on crashes). Run apps in cluster mode easily. Monitor resource usage (CPU, memory). Han…
📌 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.…
The V8 engine is a high-performance JavaScript engine developed by Google for Chrome. Node.js uses it to compile and run JavaScript code on the server side. It converts JS code into machine code, making it fast and effic…
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
sync function connect() {
const uri = 'mongodb://localhost:27017/mydatabase';
const client = new MongoClient(uri);
try {
wait client.connect();
console.log('Connected to MongoDB');
const db = client.db('mydatabase');
// Use `db` to query collections
} catch (err) {
console.error(err);
} finally {
wait client.close();
}
}
connect();
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
time per process. Clustering allows you to create multiple Node.js processes (workers)
that share the same server port. This way, your app can utilize multiple CPU cores and
handle more requests concurrently.
📌 Example: Using the built-in cluster module, you can fork multiple workers.
Node.js Node.js Tutorial · Node.js
Node.js is an open-source, cross-platform runtime environment that allows you to run
JavaScript on the server side. It’s built on the V8 JavaScript engine developed by Google
(the same one used in Chrome). With Node.js, you can build scalable and high-performance
web applications, APIs, and even real-time services like chat apps.
📌 Example:
If you write a simple HTTP server in Node.js, you can serve a webpage without using a
traditional web server like Apache:
const http = require('http');
http.createServer((req, res) => {
res.end('Hello from Node.js server!');
}).listen(3000);
Node.js Node.js Tutorial · Node.js
EventEmitter allows objects to emit named events and listen for them.
Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
emitter.emit('greet', 'Alice');
Output: Hello, Alice!
It’s fundamental for asynchronous communication in Node.js.
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
Process management means keeping your app running reliably, restarting it if it crashes, and
managing multiple instances.
PM2 is a popular Node.js process manager that:
Run your app with PM2 like this:
pm2 start app.js
pm2 monit
Node.js Node.js Tutorial · Node.js
Mongoose is an ODM (Object Data Modeling) library for MongoDB in Node.js. It provides:
You define schemas and models to interact with MongoDB more intuitively.
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
ge: Number,
createdAt: { type: Date, default: Date.now }
});
const User = mongoose.model('User', userSchema);
// Usage example
sync function createUser() {
const user = new User({ name: 'Alice', email: 'alice@example.com',
ge: 25 });
wait user.save();
console.log('User saved');
}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
Answer: nd allows async testing. It does not provide assertions, so it’s often paired with assertion libraries like Chai.
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
PM2 is a popular production process manager for Node.js applications. It helps you:
npm install pm2 -g
pm2 start app.js -i max # Runs in cluster mode with max CPU cores
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
The V8 engine is a high-performance JavaScript engine developed by Google for Chrome.
Node.js uses it to compile and run JavaScript code on the server side. It converts JS code
into machine code, making it fast and efficient.
📌 Use Case:
When you run a .js file with Node.js, the V8 engine compiles your code into machine code
behind the scenes.