Skip to content

Interview PrepRuntime · Basics

What Node.js Is ​

1. What is Node.js? ​

The short answer

Node.js is a runtime that lets you run JavaScript outside the browser, mainly on servers. It combines Google's V8 engine, which runs JavaScript, with libuv, a C library that handles files, networking, timers and a thread pool, and a standard library of modules such as http, fs and crypto. Its defining feature is non-blocking, event-driven I/O: one thread can serve many connections at once, because it never sits waiting for a slow operation to finish.

Before Node.js, JavaScript only ran in browsers. In 2009, Ryan Dahl took V8 out of Chrome, added the ability to open files and network sockets, and built everything around an event loop, so servers could handle many slow connections without one thread per connection.

What it looks like:

ts
import { createServer } from 'node:http'

const server = createServer(async (req, res) => {          // (1)
  if (req.url === '/health') {
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({ status: 'ok' }))               // (2)
    return
  }
  res.writeHead(404).end()
})

server.listen(3000, () => console.log('listening on :3000'))   // (3)
  1. One function handles every request. Node.js calls it each time a request arrives.
  2. Send the response. Nothing here blocks, so other requests are handled in between.
  3. Start listening. The process now waits, using almost no CPU, until requests arrive.

What Node.js is not:

MisconceptionReality
A programming languageIt runs JavaScript, and TypeScript once types are removed
A frameworkIt is the runtime; Express, Fastify and NestJS are frameworks on top
A web server like NginxIt can serve HTTP, but you write the server yourself
Good at everythingExcellent for I/O-heavy work; weak at long CPU-heavy computation (question 4)

Versions. Even-numbered releases become long-term support, LTS, versions supported for about 30 months. In late 2026, Node.js 24 and Node.js 26 are the current LTS lines, and from Node.js 27 the project moves to one major release a year. Production should run an LTS version.

2. How does Node.js work internally? ​

The short answer

Your JavaScript runs on one main thread inside V8. When your code asks for something slow, such as reading a file or making a network call, Node.js hands the work to libuv, which uses the operating system's non-blocking I/O for sockets and a small thread pool for things the OS cannot do asynchronously, such as many file operations and some crypto. Your code carries on immediately. When the work finishes, libuv queues your callback, and the event loop runs it on the main thread once the current code has finished.

One request, step by step, an API that reads an order from a database:

ts
app.get('/orders/:id', async (req, res) => {
  const order = await db.query('SELECT * FROM orders WHERE id = $1', [req.params.id])   // (1)
  res.json(order.rows[0])                                                               // (2)
})
main thread, V8① run handler, send queryserve other requests④ resume, send JSONlibuv② watch the socket③ reply ready: queue itoperating systemepoll, kqueue, IOCPtalks to the database
Ask, let go, get called back. ① The handler sends the query. ② libuv asks the OS to watch the connection, and the main thread moves on to other requests. ③ When the reply arrives, the callback is queued. ④ The event loop resumes the handler, which sends the response.
  1. await db.query(...) writes the query to the database socket and returns a pending promise. The handler pauses; the thread does not.
  2. When the reply arrives, the promise resolves on the main thread, the handler resumes, and the JSON is sent.

Three kinds of work, three places:

WorkWhere it runs
Your JavaScriptThe main thread, one piece at a time
Network I/O: HTTP, database, Redis socketsThe OS, asynchronously, watched by libuv
File system, DNS lookups, some crypto, compressionlibuv's thread pool, four threads by default (question 18)

The consequence: Node.js is fast as long as your JavaScript does little work per request and spends most of its time waiting. A handler that loops over a million items for 200 ms blocks every other request for those 200 ms.

3. Why would you choose Node.js for a backend application? ​

The short answer

Choose Node.js for I/O-heavy services, such as APIs, backends for front ends, real-time features with WebSockets, gateways and services that mostly call databases and other services, because its non-blocking model handles many concurrent connections cheaply. It also lets a team use one language, JavaScript or TypeScript, across front end and back end, share types and validation code, and draw on npm, the largest package ecosystem. It is less suitable for heavy CPU work, unless that work is moved to workers or other services.

Where it fits well:

UseWhy Node.js works
REST and GraphQL APIsMostly waiting on databases and other services
Real-time: chat, live dashboards, notificationsMany long-lived WebSocket connections per process
Backend for frontend, API gatewaysFan out to several services and combine results
Server-side rendering for ReactSame language and components as the front end
Streaming: uploads, proxies, file processingStreams with backpressure built in
Serverless functionsFast start-up, small memory

Where another tool may be better:

UseConcern
Video encoding, image processing at scale, machine learningCPU-bound; blocks the event loop
Heavy numeric computationJavaScript numbers and the single thread are a poor fit
Teams with deep expertise elsewhereHiring and existing code often matter more than the runtime

In an interview, give a reasoned answer, not a fan's answer: "Our service spends most of its time waiting on Postgres and two internal APIs, so a non-blocking runtime with TypeScript shared with the React app was the right fit. The one CPU-heavy job, generating PDF invoices, runs in a worker queue."

4. What are the advantages and disadvantages of Node.js? ​

The short answer

Advantages: very efficient for I/O-heavy and real-time work thanks to non-blocking I/O, one language across the whole stack, fast development with a huge package ecosystem, and good performance from the V8 engine. Disadvantages: CPU-heavy work blocks the single main thread and slows every request, so it needs workers or separate services; the npm ecosystem brings supply-chain and quality risks; and asynchronous code and error handling require discipline.

AdvantagesDisadvantages
Handles many concurrent connections with little memoryOne long CPU task blocks all requests (question 21)
Same language and types as the front endDynamic typing without TypeScript leads to runtime bugs
npm: a package for almost everythingDependency sprawl, abandoned packages, supply-chain attacks
Fast start-up, good for containers and serverlessUses one CPU core per process unless you cluster or run more instances
Streams and events built inCallback and promise mistakes can lose errors silently
Large community and hiring poolRapid ecosystem churn: frameworks and tools change often

How teams handle the weaknesses:

  1. CPU work: worker threads, a job queue, or a service in another language.
  2. One core per process: run several processes or containers behind a load balancer (question 25).
  3. Typing: TypeScript with strict on.
  4. Supply chain: lockfiles, npm ci, automated vulnerability scanning and few, well-chosen dependencies (question 81).

5. Is Node.js single-threaded or multi-threaded? ​

The short answer

Both, depending on what you mean. Your JavaScript runs on a single main thread, so two pieces of your code never run at the same moment and you do not need locks for ordinary variables. But the Node.js process itself is multi-threaded: libuv runs a thread pool, four threads by default, for file system work, DNS lookups, compression and some crypto, and V8 uses extra threads for garbage collection and compilation. You can also create more JavaScript threads yourself with worker threads.

Seeing it:

bash
node -e "setInterval(() => {}, 1000)" &
ps -T -p $!      # Linux: lists about 7 or more threads for this "single-threaded" program
ThreadDoes
Main threadRuns your JavaScript and the event loop
libuv thread pool, 4 by defaultfs, dns.lookup, zlib, crypto.pbkdf2, crypto.scrypt (question 19)
V8 background threadsGarbage collection, compiling hot code
Worker threads, if you create themExtra JavaScript threads, each with its own event loop (question 23)

Why the single JavaScript thread is a feature. In multi-threaded servers, two threads changing the same data at once cause race conditions, and you need locks. In Node.js, a block of synchronous JavaScript always runs to the end without being interrupted, so this is safe:

ts
let nextOrderNumber = 1000
function allocateOrderNumber() {
  return nextOrderNumber++          // no lock needed: nothing else runs in between
}

But races still exist across await. Between two awaits, other requests run:

ts
const stock = await getStock(sku)       // another request may run here
if (stock > 0) await reserve(sku)       // and here: two requests can both see stock = 1

That kind of race must be solved in the database, with a transaction, a conditional update or a lock.

6. Explain the architecture of Node.js? ​

The short answer

Node.js is built in layers. At the top is your JavaScript and Node's JavaScript standard library, such as fs, http and events. Underneath are C++ bindings that connect JavaScript to native code. Below them sit V8, which compiles and runs the JavaScript, and libuv, which provides the event loop, non-blocking I/O and the thread pool, plus libraries such as OpenSSL for TLS and crypto, llhttp for parsing HTTP and zlib for compression. Everything ends at the operating system.

your code: Express app, services, business logicNode.js standard library, in JavaScript: fs, http, crypto, events, streamC++ bindings: connect JavaScript calls to native codeV8runs JS, heap, GClibuvevent loop, async I/O, threadsnative librariesOpenSSL, llhttp, zlib, c-aresoperating system: Linux, macOS, Windows
JavaScript on top, C and C++ underneath. Your code calls the standard library, which calls into native code through bindings. V8 runs the JavaScript, libuv does the waiting and the threads, and other libraries do TLS, HTTP parsing and compression.

Following one call down the layers, fs.readFile('invoice.pdf', cb):

  1. Your code calls readFile.
  2. The fs module, written in JavaScript, validates the arguments and calls a binding.
  3. The C++ binding asks libuv to read the file.
  4. libuv gives the job to a thread in its pool, because file reads are not reliably asynchronous at the OS level.
  5. A pool thread makes the blocking read system call.
  6. When it finishes, libuv queues the completion, and the event loop calls your callback on the main thread.
ComponentJob
V8Parse, compile and run JavaScript; manage the heap (question 7)
libuvEvent loop, sockets, timers, thread pool, child processes (question 8)
OpenSSLTLS for HTTPS, and most of crypto
llhttpFast HTTP parsing
c-aresAsynchronous DNS for dns.resolve
zlibgzip and deflate for zlib

7. What is the V8 engine, and what does it do? ​

The short answer

V8 is Google's open-source JavaScript and WebAssembly engine, written in C++, used in Chrome and Node.js. It parses JavaScript, compiles it to bytecode that runs at once, then compiles frequently used functions to optimised machine code with its just-in-time compilers. It also manages memory: it allocates objects on its heap and frees unused ones with a generational garbage collector. Node.js embeds V8 and adds everything V8 lacks, such as files and networking.

V8 does not know about files, sockets, timers or HTTP. Those come from Node.js and libuv. V8 only runs JavaScript and manages its memory.

V8 jobDetail
ParsingSource text into a syntax tree
Ignition interpreterRuns bytecode immediately, collecting type feedback
Sparkplug, Maglev, TurboFan compilersTurn hot code into faster machine code, in stages
Hidden classes, inline cachesMake property access fast when objects have consistent shapes
Orinoco garbage collectorFrees memory in the background, in two generations (question 31)

This pipeline is explained in more detail in the JavaScript module (how JIT compilation works).

V8 settings you will use in Node.js:

bash
node --max-old-space-size=2048 server.js     # raise the old-generation heap limit to 2 GB
node --v8-options | less                     # list every V8 flag

Why version matters: each Node.js release ships a newer V8, which brings newer JavaScript features, such as new array methods, and performance improvements.

8. What is libuv, and what role does it play in Node.js? ​

The short answer

libuv is a C library that gives Node.js its asynchronous I/O and its event loop, the same way on Linux, macOS and Windows. It wraps each operating system's fastest mechanism for waiting on many sockets at once, epoll on Linux, kqueue on macOS and IOCP on Windows, runs timers, and provides a thread pool for operations the OS cannot do asynchronously, such as most file system calls and DNS lookups. Without libuv, Node.js would have no non-blocking I/O.

What libuv provides:

FeatureUsed by
Event loop with phasesEvery callback you write (question 13)
Non-blocking TCP, UDP, pipesnet, http, database drivers
TimerssetTimeout, setInterval
Thread poolfs, dns.lookup, zlib, some crypto (question 19)
Child processes and signalschild_process, process.on('SIGTERM')
File system watchingfs.watch

Why a thread pool if the OS has async I/O? Operating systems are good at waiting on many network sockets at once. They are much less consistent about asynchronous file reads, and the standard getaddrinfo DNS lookup is blocking. libuv makes those look asynchronous by running them on background threads and notifying the event loop when they finish.

A practical consequence: only four pool threads exist by default. If 50 requests each start a slow fs operation or crypto.pbkdf2, 46 of them wait for a free thread, even though the main thread is idle (question 20).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Node.js
Runtime
Memory and debugging
Data and files
Process and packages
Other topics
Nothing picked yet