Core Node.js Concepts
What is Node.js, and how is it different from traditional server-side technologies?
- Node.js is a JavaScript runtime built on Chrome’s V8 engine that runs JavaScript outside the browser. It uses an event-driven, non-blocking I/O model, making it lightweight and efficient. Unlike traditional servers (PHP, Java), it’s single-threaded and relies on asynchronous callbacks instead of multi-threading for concurrency.
Explain the event loop in Node.js.
- The event loop is a mechanism that handles asynchronous callbacks. It continuously checks for pending events and executes their callbacks in different phases (timers, pending callbacks, idle, poll, check, close). This allows Node.js to handle many requests with a single thread.
What are callbacks, and why are they used?
- Callbacks are functions passed as arguments to other functions and executed after an operation completes. They allow asynchronous, non-blocking code execution in Node.js.
Difference between process.nextTick() and setImmediate()?
process.nextTick() runs a callback before the next event loop iteration, after the current function finishes.
setImmediate() runs a callback after the current poll phase completes, on the next loop iteration.
What is non-blocking I/O?
- It means operations (like reading a file or querying a DB) are executed asynchronously, so the main thread isn’t blocked and can continue handling other requests.
How does Node.js handle single-threaded concurrency?
- By using the event loop and asynchronous callbacks, it delegates I/O operations to background workers, then processes the results when ready.
Modules and Architecture
Difference between CommonJS and ES modules?
CommonJS: require() / module.exports (synchronous, default in older Node.js).
ES modules: import / export (asynchronous, modern standard, .mjs or "type": "module" in package.json).
How to export/import in Node.js?
- CommonJS:
module.exports = myFunction;
const myFunction = require('./file');
- ES modules:
export default myFunction;
import myFunction from './file.js';
Difference between global object and module-scoped variable?
- Global variables (global) are accessible everywhere. Module-scoped variables are private to the file they’re declared in.
What is the require cache?
- Node.js caches modules after they’re loaded the first time. Subsequent require() calls return the cached version instead of reloading from disk.
Asynchronous Programming
Difference between callbacks, promises, and async/await?
Callbacks: Functions passed to handle results/errors.
Promises: Objects that represent future results (.then(), .catch()).
async/await: Syntactic sugar for promises, making code look synchronous.
How to handle multiple async calls in parallel?
- Use Promise.all([promise1, promise2])
What is Promise.all()?
- Executes multiple promises in parallel and returns results when all are resolved (or rejects if one fails).
Error handling in async/await?
- Use try...catch blocks around await calls.
File System and Streams
How to read/write files?
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {});
fs.writeFile('file.txt', 'Hello', err => {});
What are streams?
- Streams are objects for reading/writing data in chunks instead of all at once (e.g., file I/O, HTTP responses).
Types of streams?
- Readable, Writable, Duplex (both), Transform (modifies data as it passes through).
What is backpressure?
- It’s when a writable stream receives data faster than it can process; handled with .pause() and .resume() or the drain event.
Networking and HTTP
How to create an HTTP server?
const http = require('http');
http.createServer((req, res) => {
res.end('Hello World');
}).listen(3000);
Difference between http and https?
- https is HTTP over SSL/TLS, encrypting data between client and server.
How to handle CORS?
- Set headers like:
res.setHeader('Access-Control-Allow-Origin', '*');
How to parse POST data without a library?
- Listen to data and end events on req and manually parse.
Error Handling
Operational vs Programmer errors?
- Operational: Expected errors (e.g., DB connection failure).
- Programmer: Bugs in code (null reference, syntax errors).
Handle uncaught exceptions?
process.on('uncaughtException', err => { console.error(err); });
Why is domain module deprecated?
- It was a flawed way to handle async errors; now use try/catch, promises, or async/await.
Handle process-level errors?
- Use process.on('unhandledRejection', handler) and process.on('uncaughtException', handler).
Security
Prevent SQL injection?
- Use parameterized queries or ORM query builders.
What is Helmet?
- A middleware that sets security-related HTTP headers.
Prevent XSS and CSRF?
- Use HTML escaping, content security policy (CSP), CSRF tokens.
Store passwords securely?
- Use bcrypt or argon2 for hashing, never store plain text.
Performance & Scaling
Run in cluster mode?
- Use the cluster module to spawn worker processes across CPU cores.
Worker threads?
- Enable running JS in parallel threads for CPU-heavy tasks.
Detect/fix memory leaks?
- Use process.memoryUsage() and profiling tools like Chrome DevTools or clinic.js.
Improve API performance?
- Caching, load balancing, DB indexing, using async I/O efficiently.
NPM and Dependency Management
Dependencies vs devDependencies?
- dependencies are needed in production; devDependencies only for development.
Check outdated npm packages?
- Run npm outdated.
Handle version conflicts?
- Use npm dedupe or specify exact versions in package.json.
What is package-lock.json?
- Locks exact versions of installed packages for consistency across environments.
Testing
Write unit tests?
- Use frameworks like Jest/Mocha with assert or expect.
Mock dependencies?
- Use libraries like jest.mock() or sinon.
** Integration vs unit tests?**
- Unit tests check small pieces in isolation; integration tests check how modules work together.
Top comments (0)