Advertisement

Information Technology

Node.js Interview Questions & Answers

JavaScript runtime environment optimized for building scalable network apps.

40topics 400questions last updated
Advertisement

Advanced Node.js

All 15 questions
  1. libuv is the C library underlying Node.js that provides the event loop, thread pool, and asynchronous I/O abstractions across operating systems -- it handles file system operations…

  2. Running node --inspect (or --inspect-brk to pause on the first line) opens a WebSocket debugging port that Chrome DevTools or VS Code can attach to, exposing the CPU profiler, heap…

  3. process.nextTick() queues a callback to run immediately after the current operation completes, before the event loop continues to any phase -- it has the highest priority and can s…

  4. A diagnostic report (enabled via --report-uncaught-exception, --report-on-signal, or triggered programmatically) is a JSON snapshot of the process's state at a point in time -- inc…

  5. V8 optimizes object property access by internally assigning objects a 'hidden class' based on the shape (set and order of properties) of the object -- objects sharing the same shap…

Architecture & Design Patterns

All 15 questions
  1. The Module pattern uses each file's own function scope (whether via CommonJS's implicit wrapper function or ESM's module scope) to keep variables and functions private by default,…

  2. A factory function or factory class centralizes object creation logic behind a single function, hiding the specific class or configuration details from the calling code -- useful w…

  3. A Singleton ensures only one instance of a class or module-level object exists and is shared across the entire application -- in Node.js this is trivially achieved because a requir…

  4. A layered architecture separates an application into distinct responsibilities, commonly: the routing/controller layer (handling HTTP requests and responses), the service/business-…

  5. The Repository pattern defines an abstraction (an interface or a consistent set of functions) for accessing and persisting domain objects, hiding the specific database technology a…

Async Patterns

All 15 questions
  1. A callback is a function passed as an argument to another function, invoked once that function's asynchronous work completes -- Node's original core APIs (fs, http, etc.) are all b…

  2. A Promise is an object representing the eventual result of an asynchronous operation, existing in exactly one of three states at any time: pending (the operation hasn't completed y…

  3. Promise.all() resolves when every promise in the array resolves, but rejects immediately as soon as any single promise rejects (short-circuiting the rest). Promise.allSettled() alw…

  4. async/await is syntactic sugar built directly on top of Promises -- an async function always implicitly returns a Promise, and 'await' pauses execution of that specific async funct…

  5. Writing 'const a = await taskA(); const b = await taskB();' runs the two tasks sequentially -- taskB doesn't even start until taskA fully completes, wasting time when the tasks are…

Authentication & Authorization

All 15 questions
  1. Authentication verifies who a user is -- confirming their identity, typically through a username/password, a token, or a third-party identity provider. Authorization determines wha…

  2. In session-based authentication, after a successful login the server creates a session record (containing the user's identity and any relevant data) stored server-side, and sends t…

  3. A JWT is a compact, self-contained, digitally signed token used to represent claims (like a user's identity and permissions) that can be verified without needing a server-side look…

  4. A single long-lived JWT, if stolen, remains valid and dangerous for its entire lifetime. Refresh token rotation instead issues a short-lived access token (minutes) alongside a long…

  5. In the Authorization Code flow, a user is redirected to the authorization server (like Google) to log in and consent; the authorization server redirects back to the application wit…

Authentication & Authorization (JWT, OAuth, Passport)

All 5 questions
  1. They operate at different layers: OAuth 2.0 is the protocol governing how a user grants a third-party application access without sharing their password directly; JWT is a token for…

  2. Token introspection is a live call to the authorization server (via a defined OAuth endpoint) to ask 'is this token still valid, and what does it represent?' -- necessary for opaqu…

  3. Using passport-github2 (or a similar strategy package), you register the strategy with your app's client ID and secret, define a callback that receives the authenticated GitHub pro…

  4. PKCE adds a dynamically generated secret (a 'code verifier' and its hashed 'code challenge') to the Authorization Code flow, binding the initial authorization request to the specif…

  5. Verifying a JWT's signature alone only confirms it hasn't been tampered with and was signed by the expected key -- a complete verification also needs to check the 'exp' claim (has…

Background Jobs & Queues

All 15 questions
  1. A background job is a unit of work executed outside the request/response cycle -- sending emails, generating reports, processing images -- so the HTTP response can return to the us…

  2. BullMQ uses Redis as a durable, shared broker between producers (application code adding jobs) and one or more worker processes (consuming and processing jobs) -- its core building…

  3. A job is idempotent if running it more than once produces the same end result as running it exactly once -- this matters because most queue systems provide 'at-least-once' delivery…

  4. A dead-letter queue holds jobs that have permanently failed after exhausting all configured retry attempts, rather than discarding them silently -- this preserves the failed job's…

  5. A cron job runs on a fixed, recurring schedule defined by a cron expression (minute, hour, day-of-month, month, day-of-week) -- in Node.js this can be implemented with a lightweigh…

  1. Caching stores the result of an expensive operation (a database query, an API call, a computed value) temporarily, so subsequent requests for the same data can be served from the f…

  2. An in-memory cache lives entirely within a single Node.js process's memory -- extremely fast with no network overhead, but limited to that one process (useless once an application…

  3. Time-to-live (TTL) expiration simply lets cached entries expire automatically after a fixed duration -- simple, but can serve stale data until expiration. Cache-aside (lazy loading…

  4. Cache stampede occurs when a popular cached entry expires and many concurrent requests simultaneously discover the cache miss and all rush to recompute the same expensive underlyin…

  5. Cache-Control specifies directives like max-age (how long a response can be cached) and public/private (whether shared caches like CDNs may store it); ETag provides a unique finger…

Caching with Redis

All 5 questions
  1. The node-redis package (v4+) provides a promise-based client -- you create a client with createClient(), specifying the connection URL, call connect() to establish the connection,…

  2. Beyond simple key-value strings, Redis supports Hashes (field-value maps within a single key, efficient for representing an object like a user profile), Lists (ordered collections,…

  3. A distributed lock uses Redis's atomic SET with the NX (only set if not exists) and EX (expiration) options to acquire a lock -- only one instance can successfully set the key, gua…

  4. A fixed-window rate limiter increments a counter keyed by the client's identifier and current time window, setting an expiration on first creation of that key -- if the counter exc…

  5. Redis Pub/Sub lets clients subscribe to named channels and receive messages published to those channels in real time -- useful for broadcasting an event (like a chat message or a l…

Child Processes & Process Management

All 5 questions
  1. spawn() launches a command and streams its stdout/stderr incrementally, suited for long-running processes or large output. exec() runs a command through a shell and buffers its ent…

  2. fork() automatically establishes a communication channel between the parent and child, letting both sides send and receive JSON-serializable messages via process.send() (in the chi…

  3. Both exec() and execFile() support a 'timeout' option that automatically sends a kill signal to the child process if it hasn't completed within the specified duration; for spawn(),…

  4. Each child process's stdout and stdin are Node.js streams, so you can use .pipe() directly to connect one process's stdout to another's stdin, replicating a shell pipeline like 'ca…

  5. By default, a child process is tied to its parent's lifecycle in certain ways depending on the platform -- the { detached: true } option allows the child to continue running indepe…

CLI Tools & Scripting with Node.js

All 5 questions
  1. A shebang line (#!/usr/bin/env node) tells Unix-like operating systems which interpreter should execute the file when it's run directly as a program (like ./my-script.js) rather th…

  2. Rather than manually parsing process.argv (which requires hand-written logic to distinguish flags, positional arguments, and their values), libraries like commander or yargs provid…

  3. Rather than relying on OS-specific shell commands or path separators, cross-platform Node.js scripts use Node's built-in modules (fs, path) instead of shelling out to 'rm', 'cp', o…

  4. Inquirer.js provides a set of prompt types (input, list/select, checkbox for multi-select, confirm) that render interactive terminal UI, collecting a structured object of answers a…

  5. process.exitCode = n sets the exit code the process will use once it naturally finishes all pending work, without abruptly terminating the process (letting any pending I/O, like a…

Cloud & DevOps

All 15 questions
  1. The twelve-factor methodology is a set of best practices for cloud-native apps: storing configuration in environment variables (so the same build deploys unchanged across environme…

  2. Kubernetes distinguishes liveness probes (is the process alive and not deadlocked? failing restarts the container) from readiness probes (is the instance ready for traffic right no…

  3. A typical pipeline includes: installing dependencies, running linters/type checks, running the test suite, building a production artifact (a Docker image), and deploying it to stag…

  4. IaC defines cloud infrastructure in version-controlled configuration rather than manual console clicks, enabling reproducible, reviewable infrastructure changes. The AWS CDK lets t…

  5. Horizontal scaling adds more instances behind a load balancer rather than making one instance more powerful -- this requires the application to be stateless: any instance must hand…

Clustering & Worker Threads

All 15 questions
  1. A single process runs JavaScript on one main thread, using only one CPU core -- the cluster module forks multiple worker processes (typically one per core), each an independent cop…

  2. Each cluster worker is a separate OS process with its own memory -- an in-memory cache exists separately and inconsistently in each worker. The fix is moving shared state to an ext…

  3. PM2's cluster mode achieves the same goal at the process-manager level, without needing cluster-aware application code, and additionally provides zero-downtime reloads, automatic r…

  4. SharedArrayBuffer allocates memory multiple worker threads can access directly without copying -- writes from one thread are immediately visible to others, requiring careful synchr…

  5. postMessage() sends data using the structured clone algorithm, supporting most types (objects, arrays, Maps, typed arrays) but not functions or DOM nodes -- transferable objects li…

Core Node.js Modules

All 15 questions
  1. The node: prefix explicitly signals a built-in core module rather than a third-party package -- introduced partly to remove ambiguity in module resolution and support scenarios whe…

  2. util.inspect() converts a value into a formatted, human-readable string, including nested objects -- it's what console.log() uses internally (rather than JSON.stringify, which can'…

  3. The path module provides platform-aware utilities -- join(), resolve(), dirname(), extname() -- that correctly handle the difference between path separators on different OSes, wher…

  4. crypto provides hashing (createHash), symmetric/asymmetric encryption, HMAC signing, and secure random generation. Hashing is one-way, producing a fixed-size fingerprint that can't…

  5. URL and URLSearchParams (globally available, matching the browser API) provide a complete, spec-compliant way to parse a URL and manipulate query strings, handling edge cases like…

  1. A relational database (PostgreSQL, MySQL) organizes data into structured tables with a fixed schema and enforces relationships via foreign keys, well suited for data with clear, st…

  2. A connection pool maintains a set of already-established database connections that are reused across requests rather than opening and closing a new (relatively expensive to establi…

  3. A transaction groups multiple database operations so they're treated as a single atomic unit -- either every operation within it commits successfully, or if any fails, the entire t…

  4. SQL injection occurs when untrusted user input is concatenated directly into a SQL query string, letting an attacker craft input that changes the query's actual meaning (like appen…

  5. An index is a separate data structure (commonly a B-tree) that the database maintains alongside a table, allowing it to look up rows matching a specific column value without scanni…

Databases & ORMs (MongoDB/Mongoose, SQL/Sequelize)

All 5 questions
  1. Mongoose is an Object Document Mapper (ODM) for MongoDB, adding schema definition and validation (MongoDB itself is schemaless by default), typed model classes with instance and st…

  2. Sequelize defines models as JavaScript classes mapped to database tables, with each column's type and constraints declared explicitly, and relationships (one-to-many, many-to-many,…

  3. The N+1 problem occurs when fetching a list of N parent records, then separately querying for each one's related data individually (N additional queries) instead of fetching everyt…

  4. Sequelize's transaction() method wraps multiple operations so that either all of them commit together or, if any operation throws, all of them are automatically rolled back -- esse…

  5. A migration is a version-controlled script describing an incremental change to a database schema (adding a column, creating a table, adding an index) -- migration tools track which…

Debugging & Diagnostics

All 5 questions
  1. Placing a 'debugger;' statement directly in code creates a programmatic breakpoint -- when the script is run with 'node --inspect-brk' and a debugger client (Chrome DevTools or VS…

  2. Node.js can generate a heap snapshot (a complete picture of all objects currently in memory and their retaining relationships) via the --heapsnapshot-signal flag, the inspector's M…

  3. A source map maps locations in generated/compiled code back to the corresponding locations in the original source code -- without it, stack traces and debugger breakpoints for a Ty…

  4. clinic doctor runs an application under load and produces a diagnostic report highlighting likely categories of problems (event loop blocking, I/O bottlenecks, memory issues) based…

  5. The 'debug' package lets library and application code create namespaced debug loggers that are silent by default, only producing output when the DEBUG environment variable is set t…

Deployment & Process Managers (PM2)

All 5 questions
  1. Running 'node server.js' directly leaves the process with no automatic restart if it crashes, no built-in way to run multiple instances across CPU cores, no persistent log manageme…

  2. An ecosystem file defines one or more applications' configuration (script path, instance count, environment variables per environment, restart behavior, memory limits) in a single…

  3. PM2 automatically captures each managed process's stdout and stderr into log files under ~/.pm2/logs by default, but without rotation these files grow indefinitely and can eventual…

  4. PM2's 'startup' command generates and configures a system-specific init script (systemd on most modern Linux distributions) that starts PM2 itself automatically on system boot; com…

  5. 'pm2 monit' provides a real-time terminal dashboard showing each managed process's CPU usage, memory usage, and a live tail of recent log output; PM2 Plus (a paid hosted service) e…

Docker & Containerization for Node.js

All 5 questions
  1. A Dockerfile is a text file with sequential instructions describing how to build a Docker image -- for a Node.js app this typically means: starting from an official Node.js base im…

  2. A multi-stage build uses multiple FROM statements in a single Dockerfile, where an earlier stage can install build tools, dev dependencies, and compile/transpile code (like TypeScr…

  3. By default, a Docker container's process runs as root unless explicitly configured otherwise -- if an attacker manages to exploit a vulnerability in the application and achieve cod…

  4. Rather than baking environment-specific configuration into the image itself, values are injected at container runtime via -e flags, an --env-file, or docker-compose.yml's environme…

  5. Docker Compose defines multiple related services (the Node.js app, a PostgreSQL database, a Redis cache) in a single docker-compose.yml file, including their networking (services c…

Docker & Deployment

All 15 questions
  1. A Dockerfile is a text file with step-by-step instructions for building a Docker image -- for a Node.js app, this typically means starting from an official Node base image, setting…

  2. A multi-stage build uses multiple FROM statements in a single Dockerfile, where an early stage (with full build tools, dev dependencies, and a compiler) builds or compiles the appl…

  3. When Docker (or Kubernetes) stops a container, it sends SIGTERM and waits a grace period before forcibly sending SIGKILL -- a Node.js app must explicitly listen for SIGTERM and use…

  4. ENTRYPOINT defines the fixed, primary command that always runs when the container starts, while CMD provides default arguments to that entrypoint (or, if ENTRYPOINT isn't set, CMD…

  5. Running a container's process as root means that if an attacker manages to exploit a vulnerability in the application, they gain root-level access within the container, which combi…

Email & Notifications

All 15 questions
  1. Nodemailer is the most widely used Node.js library for sending email, supporting SMTP (talking directly to a mail server or provider like Gmail, SendGrid, or Amazon SES over the st…

  2. Sending an email involves a network call to an external mail provider that can be slow or occasionally fail -- doing this synchronously inside a request handler makes the user wait…

  3. SPF (Sender Policy Framework) publishes a DNS record listing which mail servers are authorized to send email on behalf of a domain, letting receiving servers verify a message wasn'…

  4. The backend uses the Firebase Admin SDK, authenticated with a service account, to send a message targeting a specific device (via a registration token the client app previously obt…

  5. A common approach defines a common Notification interface/abstraction and separate channel-specific adapters (EmailChannel, SmsChannel, PushChannel) each implementing a consistent…

Environment Variables & Configuration

All 5 questions
  1. dotenv reads key-value pairs from a local .env file and loads them into process.env at application startup, letting developers configure local environment variables (database URLs,…

  2. Validating configuration eagerly at startup (using a schema validation library like zod, joi, or envalid) causes the application to fail fast with a clear error message immediately…

  3. A common pattern centralizes all configuration access through a single config module that reads from process.env once at startup, provides sensible defaults for non-sensitive value…

  4. Build-time configuration is baked into the application artifact when it's built (like a value substituted during a bundler's build step), meaning a different value requires rebuild…

  5. Environment variables containing secrets (database passwords, API keys) can accidentally leak through overly broad logging (like logging the entire process.env object for debugging…

Error Handling

All 15 questions
  1. Operational errors are expected, recoverable failures that arise from the runtime environment or external conditions (a failed network request, invalid user input, a database conne…

  2. Extending the built-in Error class lets you attach additional context (an HTTP status code, an error code, whether the error is operational) and lets calling code distinguish error…

  3. Express supports a special error-handling middleware signature (with four parameters: err, req, res, next) placed at the end of the middleware chain -- any error passed to next(err…

  4. In Express 4 and earlier, if an async function passed as a route handler throws (or its returned promise rejects), Express's underlying error-handling doesn't automatically catch i…

  5. 4xx status codes indicate the client made a mistake (invalid input, missing authentication, requesting a nonexistent resource) -- these are typically operational errors that should…

Event Loop & Non-blocking IO

All 15 questions
  1. The event loop is the core mechanism that lets Node.js perform non-blocking I/O -- it continuously checks for completed asynchronous operations (a finished file read, an incoming n…

  2. The event loop cycles through several phases each iteration: timers (executes callbacks scheduled by setTimeout/setInterval whose time has elapsed), pending callbacks (certain syst…

  3. Non-blocking I/O means initiating an I/O operation (reading a file, querying a network resource) and immediately continuing to execute other code rather than pausing to wait for th…

  4. Event loop lag measures the delay between when a scheduled callback (like a timer) should ideally fire and when it actually does, serving as a proxy for how 'busy' or blocked the e…

  5. process.nextTick() schedules a callback to run at the very end of the current operation, before the event loop proceeds to any of its formal phases -- it has the highest possible p…

Events & EventEmitter

All 5 questions
  1. A class extends EventEmitter (from node:events) to inherit its .on(), .emit(), .once(), and .removeListener() methods, letting instances of that class emit named events at appropri…

  2. The 'error' event is treated specially by EventEmitter -- if it's emitted and there is no registered listener for it, Node.js throws the error and, by default, crashes the process,…

  3. By default, an EventEmitter instance warns (via a MaxListenersExceededWarning) if more than 10 listeners are added for the same event name -- this default limit exists specifically…

  4. .once() registers a listener that automatically removes itself after being invoked exactly one time, whereas .on() keeps a listener attached indefinitely, firing every time the eve…

  5. emit() can pass any number of additional arguments after the event name, which are delivered as separate arguments to the listener function -- but the common and generally recommen…

Express & Middleware

All 15 questions
  1. Express is a minimal, unopinionated web framework built on top of Node's core http module, providing routing (mapping URLs and HTTP methods to handler functions), middleware compos…

  2. Middleware functions receive the request, response, and a 'next' callback, executed in the exact order they're registered via app.use() or as route-specific handlers -- order matte…

  3. An async middleware function performs its await-based work and then calls next() to continue the chain, or next(err) to forward an error -- because Express (pre-v5) doesn't automat…

  4. Application-level middleware (app.use()) applies to every request reaching the app (or matching a specified path prefix). Router-level middleware works the same way but is scoped t…

  5. Validation middleware defines an expected schema for the request body, query parameters, or route parameters, validates the incoming request against it before the route handler run…

File System & File Processing

All 15 questions
  1. fs.readFile() reads an entire file into memory at once before invoking its callback with the complete contents -- simple, but problematic for large files since the whole file must…

  2. fs.readdir() with the 'recursive' option (Node 20+) returns every file and subdirectory path within a directory tree in one call, or for finer control (like filtering or processing…

  3. fs.watch() monitors a file or directory for changes, emitting events when something is modified, renamed, or removed -- but its behavior is notoriously inconsistent across operatin…

  4. Rather than checking existence with fs.access() or fs.exists() and then separately attempting to read the file (a pattern vulnerable to a race condition -- a TOCTOU, time-of-check…

  5. A direct write to a file's final path risks leaving it partially written (corrupted) if the process crashes or is killed mid-operation -- the standard atomic-write pattern instead…

File System (fs) Module

All 5 questions
  1. Every core fs operation is available in three forms: a synchronous version (like fs.readFileSync, which blocks the entire event loop until it completes -- appropriate only for star…

  2. fs.createReadStream() reads a file incrementally in chunks, emitting 'data' events (or usable via .pipe() or async iteration) as each chunk becomes available, rather than buffering…

  3. fs.watch() emits events ('change', 'rename') when the watched file or directory is modified, but its behavior is notoriously inconsistent across operating systems -- the specific e…

  4. Every open file, network socket, or pipe consumes a file descriptor, and the operating system imposes a limit on how many a single process can have open simultaneously (often 1024…

  5. fs.rename() performs an atomic move operation when the source and destination are on the same filesystem -- the file appears to move instantly with no window where it exists in nei…

File Uploads & Media Processing

All 15 questions
  1. multipart/form-data is the HTTP content type browsers use to submit forms containing file uploads, encoding each form field (including file contents) as a separate 'part' within th…

  2. multer accepts a 'fileFilter' function to reject files based on their reported MIME type or extension before they're even fully processed, and a 'limits' option to cap the maximum…

  3. sharp is a high-performance image-processing library built on the native libvips library, dramatically faster and more memory-efficient than pure-JavaScript image manipulation for…

  4. Rather than having the client upload a file to your Node.js server, which then re-uploads it to S3 (doubling bandwidth usage and tying up server resources for the duration of poten…

  5. Rather than using multer's disk storage (which writes the complete file to disk first) you can use multer's memory storage for smaller files, or for genuinely large files, use a li…

Git & Project Management

All 15 questions
  1. package-lock.json records the exact resolved version of every installed dependency (including nested transitive dependencies), ensuring that running 'npm install' produces byte-for…

  2. A monorepo houses multiple related, independently versionable packages (a shared library, a backend API, a frontend app) within a single Git repository, rather than splitting them…

  3. Git hooks are scripts that run automatically at specific points in the Git workflow (before a commit, before a push) -- Husky is a popular tool that makes configuring these hooks s…

  4. Semantic versioning uses a MAJOR.MINOR.PATCH format, where a PATCH increment indicates a backward-compatible bug fix, a MINOR increment indicates new backward-compatible functional…

  5. Conventional Commits is a specification for structuring commit messages with a type prefix (feat, fix, docs, chore, BREAKING CHANGE, and others) followed by a concise description -…

Global Objects & the process Object

All 5 questions
  1. process is a global object providing information about, and control over, the currently running Node.js process -- commonly used members include process.env (environment variables)…

  2. In CommonJS, __dirname and __filename are automatically available in every module, providing the absolute path to the current file's directory and the file itself. ES Modules don't…

  3. process.memoryUsage() returns an object describing the current process's memory usage across several categories: rss (Resident Set Size, total memory allocated for the process incl…

  4. process.on('SIGTERM', ...) and process.on('SIGINT', ...) let an application intercept termination signals sent by an orchestrator (SIGTERM, typically during a deployment or scale-d…

  5. Buffer is a global class (no require() needed) for working with raw binary data directly, predating and complementing JavaScript's later-added standard TypedArray classes -- like p…

  1. GraphQL is a query language and runtime for APIs where the client specifies exactly which fields it needs in a single request, and the server returns precisely that shape of data -…

  2. Apollo Server requires a GraphQL schema (defined using the Schema Definition Language, describing available types, queries, and mutations) and a corresponding set of resolver funct…

  3. Because each field in a GraphQL query has its own independent resolver, a query returning a list of parent objects (like 100 posts) followed by each post's author field naturally t…

  4. A Query fetches data without modifying anything, analogous to a REST GET request. A Mutation performs a write operation that changes data (creating, updating, or deleting a resourc…

  5. Authentication is typically handled the same way as a REST API -- verifying a JWT or session from the request headers before the GraphQL execution begins, attaching the resulting u…

GraphQL with Node.js

All 5 questions
  1. A GraphQL server needs a schema (written in GraphQL's Schema Definition Language, describing the available types and operations) and resolvers (functions that actually fetch or com…

  2. Because a GraphQL query can request nested related data (like a list of posts, each with their author), a naive resolver implementation ends up calling the database once per post t…

  3. Queries are for reading data and are expected to have no side effects, while Mutations are explicitly for operations that change server-side state (creating, updating, or deleting…

  4. Since GraphQL typically exposes just one HTTP endpoint (unlike REST's many distinct routes), authentication is usually handled once via a context function that runs for every reque…

  5. Over-fetching happens when a REST endpoint returns more data than the client actually needs (like a full user object when the client only wanted the name), wasting bandwidth. Under…

HTTP & HTTPS Modules

All 5 questions
  1. http.createServer() takes a callback (or listener function) that's invoked for every incoming request, receiving a request object (with method, url, and headers) and a response obj…

  2. The https module provides the same API surface as http but wraps connections in TLS encryption -- creating an HTTPS server requires providing a TLS certificate and private key (eit…

  3. Modern Node.js (v18+) includes a global fetch() function matching the browser's Fetch API, providing a much more ergonomic, promise-based interface for making HTTP requests without…

  4. HTTP keep-alive lets a single TCP connection be reused for multiple sequential HTTP requests to the same host, avoiding the overhead of establishing a new TCP (and, for HTTPS, TLS)…

  5. The http2 module provides native support for the HTTP/2 protocol, which offers multiplexed requests over a single connection (avoiding the head-of-line blocking of HTTP/1.1's conne…

HTTP & Web Servers

All 15 questions
  1. The http.createServer() function accepts a callback (or request listener) invoked for every incoming request, receiving request (req) and response (res) objects -- req provides det…

  2. HTTP/1.1 opens a new TCP connection (or reuses a limited number via keep-alive) for each set of requests, processing them largely sequentially per connection, leading to head-of-li…

  3. SSE keeps a single HTTP response open indefinitely, with the server writing formatted text events to it over time (rather than closing the connection after one response) -- the cli…

  4. Keep-alive allows a single underlying TCP connection to be reused for multiple sequential HTTP requests/responses, rather than opening and closing a brand new TCP connection (with…

  5. HTTP/2 server push lets a server proactively send resources to a client before the client explicitly requests them (like pushing a CSS file alongside the HTML page that references…

Logging & Monitoring

All 5 questions
  1. Structured logging outputs each log entry as a machine-parseable object (typically JSON) with consistent fields (timestamp, level, message, and contextual metadata) rather than a f…

  2. Log levels categorize the severity/importance of a log entry, letting a logger be configured to only actually output entries at or above a certain threshold -- typically 'debug' le…

  3. OpenTelemetry is a vendor-neutral standard and set of libraries for generating traces, metrics, and logs -- for distributed tracing specifically, each service creates 'spans' repre…

  4. A correlation (or request/trace) ID is generated once when a request first enters the system (or extracted if it was already provided by an upstream caller), attached to the reques…

  5. An APM tool (like New Relic, Datadog APM, or Dynatrace) automatically instruments an application to capture detailed performance data -- transaction traces showing exactly where ti…

Message Queues (RabbitMQ & Kafka)

All 5 questions
  1. amqplib provides a client for connecting to RabbitMQ, declaring queues (or more commonly, exchanges that route messages to queues based on rules), publishing messages to an exchang…

  2. Kafka organizes messages into topics, each split into multiple partitions for parallelism, with messages retained on disk for a configurable period (or indefinitely) rather than be…

  3. Auto-acknowledgment marks a message as successfully processed the instant it's delivered to a consumer, before any actual processing logic has even run -- if the consumer then cras…

  4. A dead-letter exchange (DLX) is configured on a queue to automatically receive messages that are rejected (nack'd without requeue), expire (via a message TTL), or exceed a queue's…

  5. Direct HTTP calls create tight temporal coupling -- both services must be available simultaneously, and the calling service blocks waiting for a response, with a failure in the dow…

Microservices Architecture with Node.js

All 5 questions
  1. Microservices allow independent deployment (a team can ship changes to one service without redeploying the entire application), independent scaling (scaling just the specific servi…

  2. In a dynamic environment (containers being created and destroyed, auto-scaling adjusting instance counts), hardcoding a downstream service's IP address doesn't work -- service disc…

  3. An API Gateway acts as a single entry point for external clients, routing incoming requests to the appropriate backend microservice, while also centralizing cross-cutting concerns…

  4. In a microservices architecture, each service should own its data exclusively, exposing it to other services only through its own API rather than allowing other services to query i…

  5. Common approaches include mutual TLS (mTLS, where each service presents a certificate verified by the other, providing strong cryptographic identity for both sides of the connectio…

Node.js Fundamentals & Runtime Architecture

All 5 questions
  1. Node.js is a JavaScript runtime built on Google Chrome's V8 engine, extended with additional APIs (file system access, networking, process management) that let JavaScript run outsi…

  2. V8 is Google's open-source, high-performance JavaScript and WebAssembly engine (also used in Chrome), responsible for parsing, compiling (via just-in-time compilation), and executi…

  3. Node.js follows a predictable release cadence where a new major version is released roughly every six months, alternating between 'Current' (receiving the latest features, but with…

  4. Node.js's single-threaded JavaScript execution model is combined with an event-driven, non-blocking I/O architecture -- when an I/O operation (a network request, a file read, a dat…

  5. npm (Node Package Manager) is the default package manager bundled with Node.js installations, providing a command-line tool for installing, publishing, and managing third-party Jav…

Path & OS Modules

All 5 questions
  1. path.join() concatenates path segments together and normalizes the result (resolving '..' and '.' segments), but doesn't guarantee an absolute path -- if all inputs are relative, t…

  2. The regular path module's behavior automatically adapts to whichever OS it's running on (using '/' on POSIX systems, '\' on Windows) -- but path.posix and path.win32 provide explic…

  3. os.platform() (returning 'win32', 'darwin', 'linux', etc.) lets a script branch its logic for OS-specific behavior, such as choosing the correct command to open a file with the sys…

  4. path.parse() breaks a path string down into an object with its component parts: root, dir, base, ext, and name (the filename without its extension) -- useful for extracting or modi…

  5. Path traversal is a vulnerability where user-supplied input containing '../' sequences is used to construct a file path, potentially letting an attacker escape an intended director…

Performance Optimization & Profiling

All 5 questions
  1. Running 'node --prof app.js' generates a V8 profiling log capturing where CPU time is spent during execution -- afterward, running 'node --prof-process' on the generated log file p…

  2. V8 initially interprets JavaScript, then compiles frequently executed ('hot') functions into optimized machine code for much faster execution -- but if that optimized function late…

  3. Load testing simulates many concurrent users or requests against an application to measure how its throughput (requests handled per second) and latency (response time, particularly…

  4. JSON.stringify() can become a measurable bottleneck for very large objects or extremely high-frequency serialization -- optimizations include using a schema-based fast serializer (…

  5. Vertical optimization improves the efficiency of the existing code and single-instance resource usage (fixing an N+1 query, adding caching, reducing unnecessary object allocation,…