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.
Method matrix
| Method | Execution | Output | Returns |
|---|---|---|---|
run(command, options?, callback?) | Shell string | Buffered by exec; streams also live | ChildProcess |
runPromise(command, options?) | Shell string | Buffered | Promise<{stdout, stderr}> with .child |
runSync(command, options?) | Shell string | Buffered | {data, err, stderr} |
runFile(file, args?, options?, callback?) | Direct executable | Buffered by execFile; streams also live | ChildProcess |
runFilePromise(file, args?, options?) | Direct executable | Buffered | Promise<{stdout, stderr}> with .child |
runFileSync(file, args?, options?) | Direct executable | Buffered | {data, err, stderr} |
runStream(file, args?, options?) | Direct executable | Unbuffered | ChildProcess |
runPromisified is the exact same function as runPromise. runFilePromisified is the exact same function as runFilePromise.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).datais 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
ChildProcessreturned by Node.
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.
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);
}
| Outcome | data | err | stderr |
|---|---|---|---|
| Success | stdout | null | null |
| Failure | null | stderr when present, otherwise the error message | captured 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.
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 asrunSync.
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).
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.
Forwarded Node options
node-cmd forwards options to the matching Node child-process method. Availability depends on that underlying method.
| Option | Purpose | Important behavior |
|---|---|---|
cwd | Child working directory | Resolve and authorize it before execution. |
env | Child environment | Supplying an object replaces the inherited environment passed by Node; include only required values. |
encoding | Buffered output encoding | Use 'buffer' or null for buffers. Not a runStream option. |
timeout | Delay before Node requests termination | Not a guaranteed wall-clock deadline or process-tree kill. |
signal | AbortSignal cancellation | Supported by asynchronous Node methods; rejection is normally an AbortError. |
shell | Select or enable a shell | Direct methods become shell-parsed when enabled. |
maxBuffer | Bound buffered stdout/stderr | Overflow terminates buffered execution. Not used by runStream. |
killSignal | Signal for timeout/cancellation | Process response is platform- and program-dependent. |
windowsHide | Hide subprocess window on Windows | Passed through where Node supports it. |
stdio | Configure direct process streams | Most relevant to runStream; synchronous wrappers default to captured pipes. |
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');child.kill() targets the immediate child according to Node and operating-system behavior. Descendants may survive, and an uncooperative process may not exit promptly.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.