All files / src/utils/node is-process-running.ts

100% Statements 10/10
100% Branches 10/10
100% Functions 1/1
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                        5x 12x 8x     4x 4x 4x   3x 1x     2x 3x                          
/**
 * Checks whether the given PID refers to a currently running process.
 *
 * This helper never throws errors. Also, if the process exists but the current user lacks permissions, it returns
 * `true` (matching the NodeJS semantics) unless `assumeDeadOnEPERM` is set to `true`.
 *
 * @example
 *
 * ```ts
 * import { isProcessRunning } from 'emitnlog/utils';
 *
 * if (isProcessRunning(process.pid)) {
 *   console.log('current process is alive');
 * }
 * ```
 *
 * @param pid The process id to check. Non-integers and values <= 0 return `false`.
 * @param options Optional behavior controls.
 * @returns `true` when a process exists for the PID, otherwise `false`.
 */
export const isProcessRunning = (pid: number, options?: Options): boolean => {
  if (pid <= 0 || !Number.isInteger(pid)) {
    return false;
  }
 
  try {
    process.kill(pid, 0);
    return true;
  } catch (error: unknown) {
    if (options?.assumeDeadOnEPERM) {
      return false;
    }
 
    const code = error && typeof error === 'object' && 'code' in error && error.code;
    return code === 'EPERM';
  }
};
 
type Options = {
  /**
   * Treat EPERM (no permissions) as a dead process.
   *
   * When `false` (default), EPERM is treated as "alive", matching NodeJS semantics for existence checks via
   * `process.kill(pid, 0)`.
   */
  readonly assumeDeadOnEPERM?: boolean;
};