Node.js applications often start external processes to perform tasks that are better handled by system tools or separate programs. A backend service might run a command-line utility to generate reports, a build server might execute compilation tools, or a scheduled job might call a script to process files.
These child processes do not always finish as expected. They can become unresponsive, wait indefinitely for an external resource, or continue running because of an unexpected condition. A process that never finishes can consume CPU and memory, hold file handles, occupy a background worker, and prevent new tasks from starting.
Node.js provides timeout options for child processes, allowing applications to limit how long an external command can run. Node.js 26.14 also introduces the subprocess.timedOut property, which helps identify whether a child process was terminated because its configured timeout expired.
This article explains how timeout detection works, how to configure time limits, and how to handle timed-out processes in production applications.
Understanding Child Process Timeouts
The Node.js child_process module provides methods for creating and managing external processes. Common methods include spawn(), exec(), and execFile().
Each method serves a different purpose:
spawn()starts a process and provides streams for handling its input and output.exec()runs a command through a shell and collects its output.execFile()executes a specified program directly without starting a shell by default.
A child process can run successfully, return an error, or remain active longer than expected. Without a timeout, an application may wait indefinitely for a command to complete.
A timeout establishes a maximum execution duration. When that duration expires, Node.js sends a termination signal to the child process. The application can then inspect the process state and decide how to handle the result.
What Is New in Node.js 26.14?
The subprocess.timedOut property provides a direct way to identify timeout-related termination.
Before using this property, developers often maintained their own timeout flags or combined several process events to determine whether a command had exceeded its execution limit.
The property makes this distinction easier. Instead of assuming that a particular exit code or termination signal always indicates a timeout, an application can inspect the ChildProcess instance.
This is useful because a process can also terminate for other reasons. For example, it might fail with a non-zero exit code, receive a signal from another part of the application, or fail to start.
The timeout indicator helps distinguish these situations and makes process monitoring easier to implement.
Configuring a Timeout With spawn()
The spawn() method is useful when an application needs to launch a process and work directly with its standard input, output, and error streams.
The timeout option specifies the maximum execution time in milliseconds. Its default value is zero, meaning that no timeout is configured.
The killSignal option determines which signal Node.js sends when the timeout expires. The default signal is SIGTERM.
The following example starts a child process with a three-second timeout:
const { spawn } = require('node:child_process');
const child = spawn(
'node',
['-e', 'setTimeout(() => {}, 15000)'],
{
timeout: 3000,
killSignal: 'SIGTERM'
}
);
child.stdout.on('data', (data) => {
console.log(`Output: ${data}`);
});
child.stderr.on('data', (data) => {
console.error(`Error output: ${data}`);
});
child.on('close', (code, signal) => {
if (child.timedOut) {
console.error('Command execution timed out.');
return;
}
console.log('Command completed.');
console.log('Exit code:', code);
console.log('Termination signal:', signal);
});The child process is designed to remain active for fifteen seconds, but the parent process allows it to run for only three seconds.
When the timeout expires, Node.js sends the configured termination signal. The application checks child.timedOut when the process closes to determine whether the timeout condition occurred.
This approach avoids maintaining a separate JavaScript timer just to identify the timeout.
Using Timeout Detection With execFile()
The execFile() method is useful when an application needs to execute a known program and collect its output. Unlike exec(), it does not start a shell by default.
The following example uses a timeout while executing another Node.js process:
const { execFile } = require('node:child_process');
const child = execFile(
'node',
['-e', 'setTimeout(() => {}, 10000)'],
{
timeout: 2500,
killSignal: 'SIGTERM'
},
(error, stdout, stderr) => {
if (child.timedOut) {
console.error('The executable exceeded the allowed time.');
return;
}
if (error) {
console.error('Command failed:', error.message);
return;
}
console.log('Command output:', stdout);
}
);In this example, the child process attempts to run for ten seconds. The parent process allows it to run for only 2.5 seconds.
The callback handles the command result, while child.timedOut indicates whether the configured timeout expired.
When using execFile(), developers should also consider the maxBuffer option. This option limits the amount of output collected in memory. Exceeding that limit is a different failure condition from a timeout and should be handled separately.
Creating a Reusable Process Execution Function
Production applications should avoid repeating process creation and timeout-handling logic throughout the codebase. A reusable function can provide consistent behavior for different commands.
The following example wraps spawn() in a Promise and returns a structured result:
const { spawn } = require('node:child_process');
function runCommand(command, args, timeout = 5000) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
timeout,
killSignal: 'SIGTERM',
stdio: ['ignore', 'pipe', 'pipe']
});
let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (data) => {
stdout += data;
});
child.stderr.on('data', (data) => {
stderr += data;
});
child.on('error', (error) => {
reject(error);
});
child.on('close', (code, signal) => {
resolve({
code,
signal,
stdout,
stderr,
timedOut: child.timedOut
});
});
});
}
async function main() {
try {
const result = await runCommand(
'node',
['-e', 'setTimeout(() => {}, 10000)'],
2000
);
if (result.timedOut) {
console.error('The command timed out.');
return;
}
if (result.code !== 0) {
console.error('The command failed:', result.stderr);
return;
}
console.log(result.stdout);
} catch (error) {
console.error('Unable to start the command:', error.message);
}
}
main();The function collects standard output and standard error, handles process creation errors, and resolves with the final process status.
The calling code can then decide whether to retry the operation, record a failure, or notify another service.
Join the conversation! Your thoughts help the community grow.