# Node.js Basics & Runtime

> What is Node.js, how does it differ from JavaScript in the browser, and which global objects does it provide?

Canonical: https://www.internhack.in/learn/interview/nodejs-interview/node-basics-runtime
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What is Node.js, how does it differ from JavaScript in the browser, and which global objects does it provide?

## Answer

Node.js is a JavaScript runtime that runs JavaScript outside the browser, built on Google's V8 engine (which compiles JavaScript to machine code) and libuv (which provides the event loop and async I/O). It adds APIs for files, networking, processes, and cryptography that browsers deliberately do not expose, which is why it is used for web servers, CLIs, build tools, and backend services.

### What Node.js is made of

- **V8**: parses, compiles, and runs your JavaScript and manages the heap and garbage collection. Same engine as Chrome.
- **libuv**: a C library that provides the event loop, the thread pool, and cross-platform async I/O.
- **Core modules**: `node:fs`, `node:http`, `node:crypto`, `node:path`, `node:stream`, `node:worker_threads` and others, written in JavaScript and C++.
- **npm**: the package manager shipped with Node (pnpm, Yarn and Bun are common alternatives).

### Node.js vs browser JavaScript

| Aspect | Browser | Node.js |
| --- | --- | --- |
| Global object | `window` (also `globalThis`) | `global` (also `globalThis`) |
| DOM | `document`, `localStorage` | None |
| System access | Sandboxed | Files, sockets, processes, env vars |
| Modules | ES modules | CommonJS and ES modules |
| Main use | UI | Servers, tooling, scripts |

The gap has narrowed. Modern Node ships many web-standard globals: `fetch`, `Request`, `Response`, `URL`, `AbortController`, `TextEncoder`, `structuredClone`, `crypto.randomUUID()`, Web Streams, and a `WebSocket` client (stable in Node 22). Recent versions can also run `.ts` files directly by stripping type annotations (enabled by default from Node 22.18 and 23.6), though a full type check still needs `tsc`.

### The global objects you should know

- **`process`**: the running process. `process.env` (environment variables, always strings), `process.argv` (CLI arguments), `process.cwd()`, `process.pid`, `process.memoryUsage()`, `process.exitCode`, and events such as `SIGTERM`, `uncaughtException`, `unhandledRejection`.
- **`Buffer`**: binary data, used by files, sockets, and crypto.
- **`globalThis` / `global`**: the global object. Prefer `globalThis`, which works everywhere.
- **Timers**: `setTimeout`, `setInterval`, `setImmediate`, `queueMicrotask`.
- **Module-scope variables in CommonJS**: `require`, `module`, `exports`, `__dirname`, `__filename`. These are not true globals; Node wraps each CJS file in a function that passes them in. In ES modules use `import.meta.dirname` and `import.meta.filename` (Node 20.11+).

### Where Node.js fits and where it does not

Node excels at I/O-bound work: APIs, gateways, chat and notification services, server-side rendering, streaming. Its single JavaScript thread is a poor fit for heavy CPU work like image processing or ML inference unless you move that work to `worker_threads`, a separate service, or native code. Since Node 15, an unhandled promise rejection crashes the process by default, so always handle rejections. For production, use an even-numbered LTS release.

**Inside the Node.js runtime. Your code calls Node APIs, which sit on V8 for execution and libuv for async I/O.**

1. **Your application code**: JavaScript or TypeScript, plus npm packages.
2. **Node.js core APIs**: fs, http, crypto, stream, process, Buffer.
3. **C++ bindings**: Bridge between JavaScript and native libraries.
4. **V8 engine**: Compiles and runs JavaScript, manages the heap.
5. **libuv**: Event loop, thread pool, cross-platform async I/O.
6. **Operating system**: Files, sockets, processes, signals.

## Code examples

### Key global objects in Node.js

```
// node app.js --port 3000
console.log('Node version:', process.version);
console.log('Platform:', process.platform);
console.log('PID:', process.pid);
console.log('CWD:', process.cwd());
console.log('Heap used (MB):', Math.round(process.memoryUsage().heapUsed / 1e6));

// argv[0] = node binary, argv[1] = script path
const args = process.argv.slice(2);
console.log('Args:', args);

// env vars are ALWAYS strings
const port = Number(process.env.PORT ?? 3000);
console.log('Port + 1 =', port + 1);

// CommonJS module-scope variables
console.log('Dir:', __dirname);

// Web-standard globals available in modern Node
console.log(typeof fetch, typeof structuredClone, crypto.randomUUID().length);
console.log(globalThis === global);
```

process exposes runtime and environment details that browser JavaScript cannot see. Environment variables are always strings, so convert them explicitly.

### Process Event Handling

```
// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
  console.error('Uncaught:', err.message);
  // Log, cleanup, then exit
  process.exit(1);
});

// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection:', reason);
});

// Graceful shutdown on SIGTERM
process.on('SIGTERM', () => {
  console.log('SIGTERM received. Shutting down...');
  server.close(() => process.exit(0));
});

// Exit event
process.on('exit', (code) => {
  console.log('Process exiting with code:', code);
});
```

Process events let you log crashes and react to signals. After an uncaughtException the process is in an unknown state, so log and exit rather than continuing. Since Node 15, an unhandled rejection crashes the process by default.

## Key points

- Node.js = V8 (runs JavaScript) + libuv (event loop and async I/O) + core modules.
- No window or document; instead you get process, Buffer, global/globalThis, and file and network access.
- \__dirname, \__filename, require and module exist only in CommonJS; ESM uses import.meta.dirname and import.meta.filename.
- Modern Node includes fetch, URL, AbortController, structuredClone, Web Streams and a WebSocket client.
- process.env values are strings; parse numbers and booleans explicitly.
- Great for I/O-bound services, weak for CPU-heavy work on the main thread.

## Common follow-up questions

- What is the difference between global and globalThis?
- Why is Node.js called single-threaded if it uses a thread pool?
- How do V8 and libuv divide responsibilities?
- What happens to a Node process when a promise rejection is not handled?

## Interview tips

- Name V8 and libuv and say what each does; that one sentence lifts a beginner answer.
- Mention that Node now ships fetch and other web APIs, which shows you are current.
- Be honest about the CPU-bound weakness and say how you would work around it.

## Concepts covered

V8 Engine, libuv, Runtime, process object, globalThis, Web APIs

Previous: [REST API Design & Middleware](https://www.internhack.in/learn/interview/nodejs-interview/node-rest-api-design) · Next: [Module System (CJS vs ESM)](https://www.internhack.in/learn/interview/nodejs-interview/node-module-system) · [All of Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)

## More Node.js Interview questions

- [File System Operations](https://www.internhack.in/learn/interview/nodejs-interview/node-fs-operations)
- [Path & OS Modules](https://www.internhack.in/learn/interview/nodejs-interview/node-path-os)
- [HTTP Module & Server Creation](https://www.internhack.in/learn/interview/nodejs-interview/node-http-server)
- [Express.js Fundamentals](https://www.internhack.in/learn/interview/nodejs-interview/node-express-fundamentals)
- [Routing & Route Parameters](https://www.internhack.in/learn/interview/nodejs-interview/node-routing-params)
- [Middleware Deep Dive](https://www.internhack.in/learn/interview/nodejs-interview/node-middleware-deep-dive)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)
