From e705603a6f0a5803599f4b85e9072737291d2db6 Mon Sep 17 00:00:00 2001 From: Erick Wendel Date: Thu, 11 Dec 2025 10:25:21 -0300 Subject: [PATCH] util: add convertProcessSignalToExitCode utility Add convertProcessSignalToExitCode() to convert signal names to POSIX exit codes (128 + signal number). Exposed in public util API. Refs: https://github.com/nodejs/node/pull/60720 PR-URL: https://github.com/nodejs/node/pull/60963 Reviewed-By: Anna Henningsen Reviewed-By: Rafael Gonzaga Reviewed-By: Moshe Atlow --- doc/api/child_process.md | 16 +++++ doc/api/util.md | 32 ++++++++++ lib/internal/util.js | 14 +++++ lib/util.js | 2 + .../test-util-convert-signal-to-exit-code.mjs | 61 +++++++++++++++++++ 5 files changed, 125 insertions(+) create mode 100644 test/parallel/test-util-convert-signal-to-exit-code.mjs diff --git a/doc/api/child_process.md b/doc/api/child_process.md index ba7cc2af6b..e3273446c3 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -1557,6 +1557,10 @@ re-raise the handled signal. See waitpid(2). +When `code` is `null` due to signal termination, you can use +[`util.convertProcessSignalToExitCode()`][] to convert the signal to a POSIX +exit code. + ### Event: `'message'` + +* `signalCode` {string} A signal name (e.g., `'SIGTERM'`, `'SIGKILL'`). +* Returns: {number|null} The exit code, or `null` if the signal is invalid. + +The `util.convertProcessSignalToExitCode()` method converts a signal name to its +corresponding POSIX exit code. Following the POSIX standard, the exit code +for a process terminated by a signal is calculated as `128 + signal number`. + +```mjs +import { convertProcessSignalToExitCode } from 'node:util'; + +console.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15) +console.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9) +console.log(convertProcessSignalToExitCode('INVALID')); // null +``` + +```cjs +const { convertProcessSignalToExitCode } = require('node:util'); + +console.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15) +console.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9) +console.log(convertProcessSignalToExitCode('INVALID')); // null +``` + +This is particularly useful when working with processes to determine +the exit code based on the signal that terminated the process. + ## `util.debuglog(section[, callback])`