Appearance
The Process and Its Lifecycle
62. What is the process object in Node.js?
The short answer
process is a global object that represents the running Node.js program and lets your code talk to its environment. It gives you environment variables in process.env, command-line arguments in process.argv, the current directory with process.cwd(), the process ID, memory and CPU usage, the standard input, output and error streams, and ways to exit with a status code. It is also an event emitter, so you listen on it for signals such as SIGTERM and for uncaught errors.
| Member | Use |
|---|---|
process.env | Environment variables (question 63) |
process.argv | Command-line arguments |
process.cwd() | The directory the process was started from (question 64) |
process.pid, process.ppid | This process's ID and its parent's |
process.memoryUsage(), cpuUsage(), uptime() | Resource use (question 30) |
process.stdin, stdout, stderr | The standard streams |
process.exitCode = 1, process.exit(1) | Ending with a status code |
process.on('SIGTERM'), on('uncaughtException') | Signals and last-resort error handling (question 65) |
process.nextTick(fn) | Schedule work right after the current operation (question 15) |
Prefer process.exitCode over process.exit(). exit() stops immediately, even if logs are still being written or responses are still being sent. Setting exitCode lets the process finish its pending work and then end with that code.
63. What are environment variables, and how is process.env used?
The short answer
Environment variables are named text values that the operating system, a container platform or a CI system gives a process when it starts, such as DATABASE_URL or NODE_ENV. They are the standard way to configure the same code differently in development, staging and production, without changing the code. In Node.js you read them from process.env, where every value is a string or undefined, so validate and convert them once at start-up and fail fast if a required one is missing.
ts
// config.ts: read and check everything once, at start-up
import { z } from 'zod'
const Env = z.object({
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
PORT: z.coerce.number().int().default(3000), // (1)
DATABASE_URL: z.string().url(), // (2)
STRIPE_SECRET_KEY: z.string().startsWith('sk_'),
LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
})
const parsed = Env.safeParse(process.env)
if (!parsed.success) {
console.error('invalid configuration', parsed.error.flatten().fieldErrors)
process.exit(1) // (3)
}
export const config = parsed.data // (4)- Every value arrives as a string, so
'3000'is converted to the number 3000. - Required values with no default.
- Fail at start-up, with a clear message, instead of crashing on the first request hours later.
- The rest of the app imports
config, typed and checked, and never touchesprocess.envdirectly.
Loading a .env file in development:
bash
node --env-file=.env dist/server.js # built into Node.jsRules to follow:
| Rule | Why |
|---|---|
Never commit .env files with secrets | They end up in Git history for ever |
| Use a secret manager in production | Secrets injected at runtime, rotated, audited |
NODE_ENV=production in production | Many libraries, including Express, turn off debug features and run faster |
Do not read process.env in hot code | It is slower than a normal object; read once into config |
64. What is the difference between process.cwd() and __dirname?
The short answer
process.cwd() is the current working directory of the process: wherever you were when you started Node.js, which can change from one run to the next. __dirname is the directory of the file whose code is running, which is always the same for that file. Use __dirname, or import.meta.dirname in ES modules, to find files that ship next to your code, such as templates. Use process.cwd() for paths the user gives relative to where they ran the command.
text
/app
dist/
server.js contains: readFile(path.join(__dirname, 'templates/receipt.html'))
templates/receipt.htmlbash
cd /app && node dist/server.js # cwd = /app, __dirname = /app/dist
cd / && node /app/dist/server.js # cwd = /, __dirname = /app/distWith readFile('templates/receipt.html'), a relative path resolved from the cwd, the first command fails and the second fails too. With path.join(__dirname, 'templates/receipt.html'), both work.
In ES modules, __dirname does not exist:
ts
import path from 'node:path'
const templates = path.join(import.meta.dirname, 'templates') // Node.js 20.11 and newer65. How should an application handle SIGINT and SIGTERM?
The short answer
SIGINT is the signal sent when you press Ctrl+C, and SIGTERM is the polite "please stop" signal that Docker, Kubernetes, systemd and most process managers send before stopping a process. Listen for both with process.on('SIGTERM', …) and start a graceful shutdown: stop accepting new work, finish what is in progress, close connections, then exit. Add a timeout, because if the process does not exit in time, the platform sends SIGKILL, which cannot be caught.
| Signal | Sent by | Can be handled | Default behaviour |
|---|---|---|---|
SIGINT | Ctrl+C in a terminal | Yes | Exit |
SIGTERM | docker stop, Kubernetes, systemd, kill <pid> | Yes | Exit |
SIGKILL | After the grace period, kill -9 | No | Immediate death |
SIGHUP | Terminal closed; sometimes "reload config" | Yes | Exit |
ts
let shuttingDown = false
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.once(signal, () => {
if (shuttingDown) return
shuttingDown = true
logger.info({ signal }, 'shutting down')
shutdown().then(() => process.exit(0), () => process.exit(1)) // (1)
})
}- Start the graceful shutdown described in question 66. Once you add a handler, Node.js no longer exits on that signal by itself, so you must exit when done.
The PID 1 trap in containers. When Node.js runs as the first process in a container, as with CMD ["node", "server.js"], the kernel does not apply default signal handling to it. Without your own handler, SIGTERM does nothing, and the container is killed after the grace period, losing in-flight requests. Handle the signals yourself, or start with a small init process such as docker run --init or tini. The Docker module explains PID 1 in depth.
npm start in production hides signals. npm may not forward SIGTERM to your Node.js process. Run node dist/server.js directly in containers.
66. How do you implement graceful shutdown in Node.js?
The short answer
On SIGTERM, first tell the load balancer you are leaving by failing the readiness check, so no new requests are sent to you. Then stop accepting new connections with server.close(), let in-flight requests finish, close idle keep-alive connections, stop background consumers, and close database pools, queues and other clients. Flush logs and metrics, then exit with code 0. Wrap it in a timeout shorter than the platform's grace period, so a stuck request cannot stop the process from exiting.
ts
import { createServer } from 'node:http'
let ready = true
app.get('/ready', (_req, res) => res.status(ready ? 200 : 503).end()) // (1)
const server = createServer(app).listen(config.PORT)
async function shutdown() {
const hardStop = setTimeout(() => { // (2)
logger.error('shutdown took too long, forcing exit')
process.exit(1)
}, 20_000)
hardStop.unref()
ready = false // (3)
await new Promise((r) => setTimeout(r, 5_000)) // (4)
await new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))) // (5)
server.closeIdleConnections() // (6)
await orderConsumer.stop() // (7)
await db.end()
await redis.quit()
await logger.flush?.()
}- Readiness reports the shutdown, so the load balancer or Kubernetes stops sending traffic (question 67).
- A deadline, shorter than the platform's grace period, which is 30 seconds by default in Kubernetes.
- Start failing readiness.
- Wait a few seconds for load balancers to notice. Without this pause, requests still in flight from the network arrive after the server has closed and fail.
server.close()stops accepting new connections and resolves when all existing ones have ended.- Close idle keep-alive connections, which would otherwise keep
closewaiting. - Stop consumers and release resources, in reverse order of start-up.
Background workers need the same care: stop taking new jobs, finish or release the current job back to the queue, then exit. A worker killed mid-job must not leave the job lost or half done, which is why queue jobs should be safe to retry.
67. How do you configure health, readiness, and liveness checks for a Node.js service?
The short answer
Expose small HTTP endpoints that the platform calls regularly. A liveness check answers "is this process healthy enough to keep running?", and should only fail when restarting would help, such as when the event loop is stuck; it should not check dependencies. A readiness check answers "should I receive traffic right now?", and fails during start-up, during shutdown, or when a dependency the service cannot work without is unavailable. Keep both fast and cheap, and configure the platform's timings to match.
ts
app.get('/live', (_req, res) => res.status(200).send('ok')) // (1)
app.get('/ready', async (_req, res) => {
if (!ready) return res.status(503).json({ status: 'shutting-down' }) // (2)
try {
await Promise.race([db.query('SELECT 1'), timeout(500)]) // (3)
res.status(200).json({ status: 'ready' })
} catch {
res.status(503).json({ status: 'db-unavailable' })
}
})- Liveness: if the process can answer at all, it is alive. A blocked event loop makes this time out, which is exactly when a restart helps.
- Readiness fails during shutdown (question 66).
- A quick check of a critical dependency, with a short timeout so the check itself cannot hang.
| Liveness | Readiness | |
|---|---|---|
| Question | Should this process be restarted? | Should this process receive traffic? |
| On failure | Restarted | Removed from the load balancer, not restarted |
| Check dependencies? | No | Only critical ones, briefly |
| Fails during start-up? | Use a startup probe instead | Yes, until ready |
The dangerous mistake: a liveness check that queries the database. When the database has a brief problem, every instance fails liveness at once, Kubernetes restarts all of them, and a short database blip becomes a full outage.
Kubernetes settings, for example:
yaml
livenessProbe:
httpGet: { path: /live, port: 3000 }
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet: { path: /ready, port: 3000 }
periodSeconds: 5
failureThreshold: 2
startupProbe:
httpGet: { path: /live, port: 3000 }
failureThreshold: 30
periodSeconds: 2Probes and their timings are covered in depth in the Kubernetes probes question.