esc-get-cmd-data-passthru-async
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

esc-get-cmd-data-passthru-async

Run any shell command, get promise resolving/rejecting (or only resolving) with

  • Return code
  • Arrays of stdout/stderr

Optional

  • Line filtering - positive/negative - using a [ function / string / regex ]
  • Data-extraction/transformation - using a [ function / regex ]
  • Pass-thru stdout/stderr (user can see cmd progress live)
  • Error handling, however you want

My other NPM modules for running commands

Interactive (run and use nano/vim/installers/htop etc)

esc-get-interactive-cmd-result-async

Capture stdout or get custom arrays on error afterwards

esc-get-cmd-stdout-array-promise

Install

npm install esc-get-cmd-data-passthru-async

Usage

Run a command and get its output as arrays. Includes powerful options for filtering, mapping, and environment control.

Silly examples with familiar commands

List files, filter, and capture output:

import { getCmdDataP } from 'esc-get-cmd-data-passthru-async';

(async () => {
  try {
    const [ retCode, outA, errA ] = await getCmdDataP(
      'ls',
      ['-la'],
      {
        cwd: '/tmp/foo',
        passthru: true,                            // Print output live (default: true)
        filterOnly: line => line.endsWith('.txt'), // Only .txt files
        capture: line => line.toUpperCase(),       // Convert to uppercase
        env: { DEBUG: '1' },
        verbosity: 3,                              // Verbose logs (default: 3)
      }
    );
    console.log('retCode:', retCode);
    console.log('Stdout array:', outA);
    console.log('Stderr array:', errA);
  } catch ([ retCode, outA, errA ]) {
    console.error('retCode', retCode);
    console.log('Stdout array:', outA);
    console.log('Stderr array:', errA);
  }
})();

Silly one line examples

const [ retCode, outA, errA ] = await getCmdDataP('apt', ['update'], { capture:/https?:\/\/[^ ]+/ }); // get only the apt URL's
const [ retCode, outA, errA ] = await getCmdDataP('apt', ['update'], { filterOnly:'Hit', filterNot:'debian.org/' }); // Only get the lines containing Hit, but not the debian.org related lines.
const [ retCode, outA, errA ] = await getCmdDataP('apt', ['update'], { filterOnly:/(E|Err):/ }); // get only the apt URL's
const [ retCode, outA, errA ] = await getCmdDataP('df', ['-h'], { filterOnly:/(^Filesystem | \/$)/ }); // Get the headings and only the root filesystem's stats
const [ retCode, outA, errA ] = await getCmdDataP('zfs', ['list','yourmom'], { filterNot:/^NAME / });

Ping foo-pc with an interval of 0.5 seconds, timeout of 2 sec per ping, max 5 attempts, stop immediately when you get a reply, capture/return the milliseconds.

    const [ retCode, outA, errA ] = await getCmdDataP('ping', ['-i', '0.5', '-W', '2', '-c', '5', 'foo-pc'], { capture:/bytes from.+time=([\d.]+)/, until:'bytes from' });

API

getCmdDataP(cmd, argsA=[], optionsO={})

  • cmd: String – Command to run.
  • argsA: Array<string> – Command arguments.
  • optionsO: Object
    • passthru: Boolean (default: true) – Print stdout/stderr to terminal live.
    • filterOnly: Function/RegExp/String – Include only lines matching this.
    • filterNot: Function/RegExp/String – Exclude lines matching this.
    • capture: Function/RegExp – Map/transforms each line before collecting.
    • until: Function/RegExp/String – Stop (kill process) once a match is seen:
      • Function: receives all new output lines, stop if returns truthy
      • String: stop if any new line includes it
      • RegExp: stop if any new line matches
    • verbosity: 0-3 (default:3) – Control log output:
      • 0:silent, 1:errors, 2:show commands, 3:show success
    • env: Object – Extra environment variables (merged with process.env).
    • spawnO: Object – Additional options for child_process.spawn.
    • rejectOnError: Boolean (default:true) – Rejects promise on error/exit code != 0. If false, always resolves.

Capture groups in capture regex

  • If you have no capture groups, you get the whole match.
  • If you have 1 capture group, you get what you captured.
  • If you have 2+ capture groups, you get an array of your captures

Your capture groups should (not)? be optional. If you make them optional you will have to deal with a varying output format caused by your 🐂💩 regex.

Returns

A Promise resolving to:

[ exitCode, outA, errA ]
  • exitCode: 0 on success; else reject with code > 0
  • outA: Array of (possibly filtered/transformed) stdout lines
  • errA: Array of (possibly filtered/transformed) stderr lines

Features

  • No dependencies: Simple, fast, no bloat.
  • Small: Only 6k of code
  • Stable API: No breaking changes will ever be made.
  • Passthrough: See output live by default, or disable for silent/asynchronous capture.
  • Filtering/Mapping: Pick or modify output lines with strings, RegExp, or functions.
  • Great for automation: User can watch progress, calling script gets all of the data output.
  • No noise: Get only the data that you need
  • Flexible Environment: Pass custom env variables, cwd, etc.
  • Powerful: Get shit done!

Typical Scenarios

  • Running build scripts, CLI tools, or diagnostics within Node.js
  • Filtering logs, capturing only what you want from output
  • Replacing heavy solutions like zx with something lighter, safer, and more transparent

License

MIT


Say thanks by starring: esc-get-cmd-data-passthru-async on GitHub
Issues & PRs welcome!


Package Sidebar

Install

npm i esc-get-cmd-data-passthru-async

Weekly Downloads

19

Version

0.1.4

License

MIT

Unpacked Size

16.1 kB

Total Files

5

Last publish

Collaborators

  • softwarecreations