Comprehensive nodejs fundamentals & architecture interview questions and answers for Node.js.
Prepare for your next job interview with expert guidance.
Node.js architecture consists of several key components: 1) V8 Engine: Google's open-source JavaScript engine that compiles JS to native machine code, 2) libuv: Handles async operations, event loop, and thread pool, 3) Core Modules: Built-in modules like http, fs, path, 4) Node Standard Library: JavaScript implementation of core functionality, 5) Node Package Manager (NPM): Package management system. This architecture enables efficient, non-blocking operations and cross-platform compatibility.
Key differences include: 1) Global object: 'window' in browsers vs 'global' in Node.js, 2) DOM/BOM APIs only available in browsers, 3) File system access available in Node.js but not browsers, 4) Module systems: CommonJS in Node.js vs ES Modules in modern browsers, 5) Threading: Web Workers in browsers vs Worker Threads in Node.js, 6) Different security models and constraints. Understanding these differences is crucial for Node.js development.
Core modules are built-in modules that come with Node.js installation: 1) No installation required (http, fs, path), 2) Higher performance as they're preloaded, 3) Fundamental functionality implementation, 4) Written in C++ for performance. External modules are third-party modules installed via NPM. Example: const http = require('http'); // core module vs const express = require('express'); // external module
CommonJS implementation in Node.js includes: 1) require() function for module loading, 2) module.exports for exposing functionality, 3) Module caching for performance, 4) Module resolution algorithm. Example: // math.js module.exports = { add: (a, b) => a + b }; // main.js const math = require('./math'); console.log(math.add(2, 3)); // Module loading is synchronous and cached
Node.js uses V8's garbage collection with two main phases: 1) Scavenge: Fast but partial collection for young objects, 2) Mark-Sweep: Complete collection for old objects. Features include: 1) Generational collection, 2) Incremental marking, 3) Concurrent sweeping, 4) Memory optimization flags. Example of manual GC trigger (not recommended): global.gc(); // requires --expose-gc flag
Error handling in Node.js includes: 1) Try-catch blocks for synchronous code, 2) Error events for EventEmitter, 3) Error-first callbacks for async operations, 4) Promise rejection handling, 5) Global error handlers. Example: process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled Rejection at:', promise, 'reason:', reason); }); try { throw new Error('Sync Error'); } catch (err) { console.error(err); }
Timing functions in Node.js: 1) process.nextTick(): Executes callback before next event loop iteration, 2) setImmediate(): Executes in check phase of event loop. Key differences: nextTick has higher priority and runs before I/O events. Example: process.nextTick(() => console.log('nextTick')); setImmediate(() => console.log('setImmediate'));
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. Key features include: 1) Event-driven and non-blocking I/O model, 2) Single-threaded event loop with asynchronous programming, 3) NPM (Node Package Manager) for package management, 4) Built-in modules for file system operations, networking, etc., 5) Cross-platform support, 6) Active community and extensive ecosystem.
V8 Engine in Node.js: 1) Compiles JavaScript to machine code, 2) Manages memory allocation, 3) Handles garbage collection, 4) Provides data types and objects, 5) Optimizes code execution. Features include: JIT compilation, inline caching, hidden classes for optimization. Example of V8 flags: node --v8-options --optimize_for_size --max_old_space_size=1024 app.js
REPL (Read-Eval-Print-Loop) provides an interactive shell for Node.js: 1) Testing code snippets, 2) Debugging, 3) Experimenting with Node.js features, 4) Quick prototyping. Features include: Auto-completion, Multi-line editing, Command history. Example: node // enters REPL > const sum = (a, b) => a + b; > sum(2, 3) // 5
Clustering enables running multiple Node.js processes: 1) Master process creates worker processes, 2) Workers share server ports, 3) Load balancing between workers, 4) IPC communication between processes. Example: const cluster = require('cluster'); if (cluster.isMaster) { cluster.fork(); cluster.fork(); } else { require('./server.js'); }
Child processes in Node.js: 1) spawn(): Streams for large data, 2) exec(): Buffers for completion, 3) fork(): IPC channel for Node.js processes, 4) execFile(): Execute executable files. Example: const { spawn } = require('child_process'); const ls = spawn('ls', ['-l']); ls.stdout.on('data', (data) => console.log(data.toString()));
ES modules support in Node.js includes: 1) .mjs extension for ES module files, 2) 'type': 'module' in package.json, 3) Import/export syntax, 4) Dynamic imports, 5) Module resolution rules. Example: // file.mjs export const hello = 'world'; import { hello } from './file.mjs'; // Dynamic import: const module = await import('./module.mjs');
Buffers handle binary data in Node.js: 1) Buffer: Node.js specific for binary data, 2) ArrayBuffer: JavaScript standard binary data container. Features: Direct memory allocation, Binary data operations, Encoding conversions. Example: const buf = Buffer.from('Hello', 'utf8'); console.log(buf); // <Buffer 48 65 6c 6c 6f> console.log(buf.toString()); // Hello
libuv is a multi-platform support library that handles: 1) Asynchronous I/O operations, 2) Thread pool management, 3) Event loop implementation, 4) Network operations, 5) File system operations, 6) Inter-process communication. It abstracts underlying OS differences and provides a consistent async I/O interface across platforms. Example: const fs = require('fs'); fs.readFile('file.txt', (err, data) => {}); // handled by libuv behind the scenes
In Node.js: 1) Process: Instance of a program in execution with its own memory space, 2) Main Thread: Single thread running event loop, 3) Worker Threads: Additional threads for CPU-intensive tasks, 4) Thread Pool: Managed by libuv for async operations. Example using worker threads: const { Worker } = require('worker_threads'); const worker = new Worker('./worker.js'); worker.postMessage('start'); worker.on('message', (result) => console.log(result));
The process object provides information and control over the Node.js process: 1) Environment variables (process.env), 2) Command line arguments (process.argv), 3) Process control (process.exit()), 4) Event handling for process lifecycle, 5) CPU and memory usage information. Example: process.on('uncaughtException', (err) => { console.error('Uncaught Exception:', err); process.exit(1); });
Key differences include: 1) LTS (Long Term Support): Stable, production-ready, 30-month support cycle, 2) Current: Latest features, shorter support cycle, potentially unstable. LTS focuses on stability and security, while Current provides newest features. Release schedule: New major version every 6 months, LTS versions released yearly.