Reference node-cmd v6

API reference

Exact signatures, execution boundaries, return values, error behavior, and lifecycle control for every exported method.

01 / Load

CommonJS and native ES modules in Node.js

CommonJS

const cmd = require('node-cmd');

const { run, runFile, runStream } = cmd;

Node.js ES modules

import cmd, {
    run,
    runFile,
    runStream
} from 'node-cmd';

The default export and named exports point to the same implementations. Existing deep imports through node-cmd/cmd and node-cmd/cmd.js remain exported for compatibility; new code should import the package root.

02 / Surface

Method matrix

MethodExecutionOutputReturns
run(command, options?, callback?)Shell stringBuffered by exec; streams also liveChildProcess
runPromise(command, options?)Shell stringBufferedPromise<{stdout, stderr}> with .child
runSync(command, options?)Shell stringBuffered{data, err, stderr}
runFile(file, args?, options?, callback?)Direct executableBuffered by execFile; streams also liveChildProcess
runFilePromise(file, args?, options?)Direct executableBufferedPromise<{stdout, stderr}> with .child
runFileSync(file, args?, options?)Direct executableBuffered{data, err, stderr}
runStream(file, args?, options?)Direct executableUnbufferedChildProcess
Aliases. runPromisified is the exact same function as runPromise. runFilePromisified is the exact same function as runFilePromise.
03 / Shell async

run(command, options?, callback?)

Starts command through the platform shell using Node’s child_process.exec(). Shell syntax—including pipes, redirection, substitutions, and separators—is interpreted by that shell.

const child = cmd.run(
    'git status --short',
    { cwd: './project', timeout: 30_000 },
    (error, stdout, stderr) => {
        if (error) {
            console.error(stderr || error.message);
            return;
        }
        console.log(stdout);
    }
);

console.log(child.pid);
Callback
(error, data, stderr). data is stdout, preserving the classic node-cmd callback name.
Without callback
The command still starts. Consume child.stdout, child.stderr, and lifecycle events directly.
Return
Always the immediate ChildProcess returned by Node.
04 / Shell Promise

runPromise(command, options?)

Runs the same shell-string path and resolves after buffered execution completes.

const task = cmd.runPromise('npm test', {
    cwd: './project',
    timeout: 30_000
});

console.log(task.child.pid);
const { stdout, stderr } = await task;

The Promise exposes Node’s immediate process handle as task.child. On nonzero exit, timeout, buffer overflow, or cancellation, it rejects with Node’s execution error; collected stdout and stderr remain attached to that error.

05 / Shell sync

runSync(command, options?)

Uses execSync() and preserves node-cmd’s non-throwing result envelope for ordinary execution and validation failures.

const result = cmd.runSync('node --version');

if (result.err) {
    console.error(result.stderr || result.err);
} else {
    console.log(result.data);
}
Outcomedataerrstderr
Successstdoutnullnull
Failurenullstderr when present, otherwise the error messagecaptured stderr or an empty value

Defaults are encoding: 'utf8' and stdio: 'pipe'. Explicit non-undefined option values win. Use encoding: 'buffer' or null for buffers.

06 / Direct buffered

runFile*

The direct methods call Node’s execFile family. The executable and arguments stay separate, and no shell starts unless options.shell is explicitly enabled.

const values = ['with spaces', 'semi;colon', 'ampersand&value'];

const { stdout } = await cmd.runFilePromise(
    'tool',
    ['--format', 'json', '--value', ...values],
    { cwd: './project' }
);
runFile
Callback form; returns the immediate ChildProcess.
runFilePromise
Resolves {stdout, stderr}; the returned Promise exposes .child.
runFileSync
Returns the same {data, err, stderr} envelope as runSync.

args may be omitted, undefined, or null. An options object may occupy that position. Callback overloads accept (file, callback), (file, args, callback), (file, options, callback), and (file, args, options, callback).

07 / Direct streaming

runStream(file, args?, options?)

Wraps child_process.spawn() for long-running, interactive, or high-output programs. Output is not accumulated into a final object, so maxBuffer and buffered-output encoding do not apply.

const child = cmd.runStream(
    'node',
    ['worker.js'],
    { stdio: ['pipe', 'pipe', 'pipe'] }
);

child.stdout.setEncoding('utf8');
child.stdout.on('data', console.log);
child.stdin.write('start\n');
child.once('close', (code, signal) => {
    console.log({ code, signal });
});

Set stream encodings on the streams themselves. The no-shell default keeps each element of args as one argument. Enabling options.shell restores shell parsing and its security implications.

08 / Options

Forwarded Node options

node-cmd forwards options to the matching Node child-process method. Availability depends on that underlying method.

OptionPurposeImportant behavior
cwdChild working directoryResolve and authorize it before execution.
envChild environmentSupplying an object replaces the inherited environment passed by Node; include only required values.
encodingBuffered output encodingUse 'buffer' or null for buffers. Not a runStream option.
timeoutDelay before Node requests terminationNot a guaranteed wall-clock deadline or process-tree kill.
signalAbortSignal cancellationSupported by asynchronous Node methods; rejection is normally an AbortError.
shellSelect or enable a shellDirect methods become shell-parsed when enabled.
maxBufferBound buffered stdout/stderrOverflow terminates buffered execution. Not used by runStream.
killSignalSignal for timeout/cancellationProcess response is platform- and program-dependent.
windowsHideHide subprocess window on WindowsPassed through where Node supports it.
stdioConfigure direct process streamsMost relevant to runStream; synchronous wrappers default to captured pipes.
09 / Lifecycle

ChildProcess control, cancellation, and failure

Abort buffered work

const controller = new AbortController();
const task = cmd.runPromise(command, {
    signal: controller.signal
});

controller.abort();
await task;

Terminate manually

const child = cmd.runStream(file, args);

child.once('error', handleStartError);
child.once('close', handleClose);
child.kill('SIGTERM');
Process-tree boundary. A timeout, abort, or child.kill() targets the immediate child according to Node and operating-system behavior. Descendants may survive, and an uncooperative process may not exit promptly.
10 / Platform

Cross-platform contract

Shell strings normally use /bin/sh on Unix-like systems and ComSpec on Windows. Quoting, expansion, separators, and built-ins differ. Prefer runFile* or runStream for portable executable calls. Windows .bat and .cmd files require a command shell.

node-cmd does not request administrator, root, or UAC elevation. Children inherit the privileges of the Node.js process that starts them.