2.2.0 • Published 6 months ago

teen_process v2.2.0

Weekly downloads
92,873
License
Apache-2.0
Repository
github
Last release
6 months ago

node-teen_process

A grown-up version of Node's child_process. exec is really useful, but it suffers many limitations. This is an es7 (async/await) implementation of exec that uses spawn under the hood. It takes care of wrapping commands and arguments so we don't have to care about escaping spaces. It can also return stdout/stderr even when the command fails, or times out. Importantly, it's also not susceptible to max buffer issues.

teen_process.exec

Examples:

import { exec } from 'teen_process';

// basic usage
let {stdout, stderr, code} = await exec('ls', ['/usr/local/bin']);
console.log(stdout.split("\n"));  // array of files
console.log(stderr);              // ''
console.log(code);                // 0

// works with spaces
await exec('/command/with spaces.sh', ['foo', 'argument with spaces'])
// as though we had run: "/command/with spaces.sh" foo "argument with spaces"

// nice error handling that still includes stderr/stdout/code
try {
  await exec('echo_and_exit', ['foo', '10']);
} catch (e) {
  console.log(e.message);  // "Exited with code 10"
  console.log(e.stdout);   // "foo"
  console.log(e.code);     // 10
}

The exec function takes some options, with these defaults:

{
  cwd: undefined,
  env: process.env,
  timeout: null,
  killSignal: 'SIGTERM',
  encoding: 'utf8',
  ignoreOutput: false,
  stdio: "inherit",
  isBuffer: false,
  shell: undefined,
  logger: undefined,
  maxStdoutBufferSize: 100 * 1024 * 1024, // 100 MB
  maxStderrBufferSize: 100 * 1024 * 1024, // 100 MB
}

Most of these are self-explanatory. ignoreOutput is useful if you have a very chatty process whose output you don't care about and don't want to add it to the memory consumed by your program.

Both buffer size limits are needed to avoid memory overflow while collecting process output. If the overall size of output chunks for different stream types exceeds the the given one then the oldest chunks will be pulled out in order to keep the memory load within the acceptable ranges.

If you're on Windows, you'll want to pass shell: true, because exec actually uses spawn under the hood, and is therefore subject to the issues noted about Windows + spawn in the Node docs.

If stdio option is not set to inheirt, you may not get colored output from your process. In this case you can explore the subprocess's documentation to see if an option like --colors or FORCE_COLORS can be specified. you can also try to set env.FORCE_COLOR = true and see if it works.

Example:

try {
  await exec('sleep', ['10'], {timeout: 500, killSignal: 'SIGINT'});
} catch (e) {
  console.log(e.message);  // "'sleep 10' timed out after 500ms"
}

The isBuffer option specifies that the returned standard I/O is an instance of a Buffer.

Example:

let {stdout, stderr} = await exec('cat', [filename], {isBuffer: true});
Buffer.isBuffer(stdout); // true

The logger option allows stdout and stderr to be sent to a particular logger, as it it received. This is overridden by the ignoreOutput option.

teen_process.SubProcess

spawn is already pretty great but for some uses there's a fair amount of boilerplate, especially when using in an async/await context. teen_process also exposes a SubProcess class, which can be used to cut down on some boilerplate. It has 2 methods, start and stop:

import { SubProcess } from 'teen_process';

async function tailFileForABit () {
  let proc = new SubProcess('tail', ['-f', '/var/log/foo.log']);
  await proc.start();
  await proc.stop();
}

Errors with start/stop are thrown in the calling context.

Events

You can listen to 8 events:

  • exit
  • stop
  • end
  • die
  • output
  • lines-stdout
  • lines-stderr
  • stream-line
proc.on('exit', (code, signal) => {
  // if we get here, all we know is that the proc exited
  console.log(`exited with code ${code} from signal ${signal}`);
  // exited with code 127 from signal SIGHUP
});

proc.on('stop', (code, signal) => {
  // if we get here, we know that we intentionally stopped the proc
  // by calling proc.stop
});

proc.on('end', (code, signal) => {
  // if we get here, we know that the process stopped outside of our control
  // but with a 0 exit code
});

proc.on('die', (code, signal) => {
  // if we get here, we know that the process stopped outside of our control
  // with a non-zero exit code
});

proc.on('output', (stdout, stderr) => {
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

// lines-stderr is just the same
proc.on('lines-stdout', lines => {
  console.log(lines);
  // ['foo', 'bar', 'baz']
  // automatically handles rejoining lines across stream chunks
});

// stream-line gives you one line at a time, with [STDOUT] or [STDERR]
// prepended
proc.on('stream-line', line => {
  console.log(line);
  // [STDOUT] foo
});
// so we could do: proc.on('stream-line', console.log.bind(console))

Start Detectors

How does SubProcess know when to return control from start()? Well, the default is to wait until there is some output. You can also pass in a number, which will cause it to wait for that number of ms, or a function (which I call a startDetector) which takes stdout and stderr and returns true when you want control back. Examples:

await proc.start(); // will continue when stdout or stderr has received data
await proc.start(0); // will continue immediately

let sd = (stdout, stderr) => {
  return stderr.indexOf('blarg') !== -1;
};
await proc.start(sd); // will continue when stderr receives 'blarg'

A custom startDetector can also throw an error if it wants to declare the start unsuccessful. For example, if we know that the first output might contain a string which invalidates the process (for us), we could define a custom startDetector as follows:

let sd = (stdout, stderr) => {
  if (/fail/.test(stderr)) {
    throw new Error("Encountered failure condition");
  }
  return stdout || stderr;
};
await proc.start(sd); // will continue when output is received that doesn't
                      // match 'fail'

Finally, if you want to specify a maximum time to wait for a process to start, you can do that by passing a second parameter in milliseconds to start():

// use the default startDetector and throw an error if we wait for more than
// 1000ms for output
await proc.start(null, 1000);

Finishing Processes

After the process has been started you can use join() to wait for it to finish on its own:

await proc.join(); // will throw on exitcode not 0
await proc.join([0, 1]); // will throw on exitcode not 0 or 1

And how about killing the processes? Can you provide a custom signal, instead of using the default SIGTERM? Why yes:

await proc.stop('SIGHUP');

If your process might not be killable and you don't really care, you can also pass a timeout, which will return control to you in the form of an error after the timeout has passed:

try {
  await proc.stop('SIGHUP', 1000);
} catch (e) {
  console.log("Proc failed to stop, ignoring cause YOLO");
}

All in all, this makes it super simple to, say, write a script that tails a file for X seconds and then stops, using async/await and pretty straightforward error handling.

async function boredTail (filePath, boredAfter = 10000) {
  let p = new SubProcess('tail', ['-f', filePath]);
  p.on('stream-line', console.log);
  await p.start();
  await Bluebird.delay(boredAfter);
  await p.stop();
}
@infinitebrahmanuniverse/nolb-tee@everything-registry/sub-chunk-2885io.appium.settingskuben-appium-ios-driverkuben-appium-ios-simswitchkuben-appium-ios-simulatorkuben-appium-ios-testkuben-appium-xcodekuben-appium-xcuitest-driverkuben-node-simctlgst-atom-adbgst-atom-android-drivergst-atom-ios-drivergst-atom-uiautomator2-drivergst-atom-xcuitest-driverjonahss-is-testingmx-appiummx-appium-base-drivermx-appium-desktopmatt-appium-doctornode-scrcpynode-sim-clinode-simctlrun-ios-devicetermux-appiumtransfer-mp4-to-hls@appium/plugin-test-support@appium/support@appium/doctor@appium/docutils@applitools/execution-grid-tunnel@astound/appium-xcuitest-driverappium-plus2webgram@ltservices/appium-youiengine-driver@londoner/appium@magic-pod/appium@massfice/sw-fairy-common-development-scripts@stevenzeng/mp-test-starter@stdspa/appium-linux-driver@rpai/appium-chromium-driverexec-applescript-testali-usb_ctlforked-driverblackcombappium-remote-debuggerappium-roku-driverappium-safari-driverappium-sdbappium-selendroid-driverappium-selendroid-driver-allotappium-selendroid-installerappium-skywheel-driverappium-supportappium-uiautomator2-driverappium-uiautomator2-driver-cmextappium-uiautomator2-driver-conanappium-uiautomator2-driver-how-to-add-handlerappium-uiautomator2-driver-how-to-add-new-handlerappium-uiautomator2-driver-testappium-uiautomator2-driver-test-1appium-uiautomator2-installerappium-tizen-driverappium-tizen-tv-driverappium-uiautoappium-uiautomator2-drive-how-to-add-new-handlerappium-mac2-driverappium-multisimappium-nodeappium-testappium-adbappium-adb-testappium-android-bootstrapappiumappium-webdriveragentappium-webdriveragent-driverappium-webdriveragent-iosappium-webos-driverappium-windows-driverappium-withloggingappium-youi-driverappium-youiengine-driverappiumx-helios-driverappium-xcuitest-driverappium-xcuitest-driver-conanappium-xcuitest-driver-iosappium-zhouappium2appiumvmappiumxappiumx-base-driverappium-xcodeappium-base-driver-testappium-base-driver-test-1appium-chromedriverappium-crosswalkappium-desktopappium-doctorappium-espresso-driverappium-android-driver-conan
2.1.9

6 months ago

2.1.10

6 months ago

2.2.0

6 months ago

2.1.4

7 months ago

2.1.6

6 months ago

2.1.5

6 months ago

2.1.8

6 months ago

2.1.7

6 months ago

2.1.2

7 months ago

2.1.3

7 months ago

2.0.112

1 year ago

2.0.111

1 year ago

2.1.1

1 year ago

2.1.0

1 year ago

2.0.109

1 year ago

2.0.110

1 year ago

2.0.69

1 year ago

2.0.79

1 year ago

2.0.77

1 year ago

2.0.78

1 year ago

2.0.75

1 year ago

2.0.76

1 year ago

2.0.73

1 year ago

2.0.74

1 year ago

2.0.71

1 year ago

2.0.72

1 year ago

2.0.70

1 year ago

2.0.108

1 year ago

2.0.107

1 year ago

2.0.106

1 year ago

2.0.105

1 year ago

2.0.104

1 year ago

2.0.88

1 year ago

2.0.103

1 year ago

2.0.89

1 year ago

2.0.102

1 year ago

2.0.86

1 year ago

2.0.101

1 year ago

2.0.87

1 year ago

2.0.100

1 year ago

2.0.84

1 year ago

2.0.85

1 year ago

2.0.82

1 year ago

2.0.83

1 year ago

2.0.80

1 year ago

2.0.81

1 year ago

2.0.99

1 year ago

2.0.97

1 year ago

2.0.98

1 year ago

2.0.95

1 year ago

2.0.96

1 year ago

2.0.93

1 year ago

2.0.94

1 year ago

2.0.91

1 year ago

2.0.92

1 year ago

2.0.90

1 year ago

2.0.39

1 year ago

2.0.48

1 year ago

2.0.49

1 year ago

2.0.46

1 year ago

2.0.47

1 year ago

2.0.44

1 year ago

2.0.45

1 year ago

2.0.42

1 year ago

2.0.43

1 year ago

2.0.40

1 year ago

2.0.41

1 year ago

2.0.59

1 year ago

2.0.57

1 year ago

2.0.58

1 year ago

2.0.55

1 year ago

2.0.56

1 year ago

2.0.53

1 year ago

2.0.54

1 year ago

2.0.51

1 year ago

2.0.52

1 year ago

2.0.50

1 year ago

2.0.68

1 year ago

2.0.66

1 year ago

2.0.67

1 year ago

2.0.64

1 year ago

2.0.65

1 year ago

2.0.62

1 year ago

2.0.63

1 year ago

2.0.60

1 year ago

2.0.61

1 year ago

2.0.28

1 year ago

2.0.29

1 year ago

2.0.37

1 year ago

2.0.3

2 years ago

2.0.38

1 year ago

2.0.35

1 year ago

2.0.5

1 year ago

2.0.36

1 year ago

2.0.4

2 years ago

2.0.33

1 year ago

2.0.7

1 year ago

2.0.34

1 year ago

2.0.6

1 year ago

2.0.31

1 year ago

2.0.9

1 year ago

2.0.32

1 year ago

2.0.8

1 year ago

2.0.30

1 year ago

2.0.15

1 year ago

2.0.16

1 year ago

2.0.13

1 year ago

2.0.14

1 year ago

2.0.11

1 year ago

2.0.12

1 year ago

2.0.10

1 year ago

2.0.19

1 year ago

2.0.17

1 year ago

2.0.18

1 year ago

2.0.26

1 year ago

2.0.27

1 year ago

2.0.24

1 year ago

2.0.25

1 year ago

2.0.22

1 year ago

2.0.23

1 year ago

2.0.20

1 year ago

2.0.21

1 year ago

2.0.2

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

1.16.0

4 years ago

1.15.0

5 years ago

1.14.3

5 years ago

1.14.2

6 years ago

1.14.1

6 years ago

1.14.0

6 years ago

1.13.1

6 years ago

1.13.0

6 years ago

1.12.1

7 years ago

1.12.0

7 years ago

1.11.0

7 years ago

1.10.1

7 years ago

1.10.0

7 years ago

1.9.0

8 years ago

1.8.2

8 years ago

1.8.1

8 years ago

1.8.0

8 years ago

1.6.2

8 years ago

1.7.1

8 years ago

1.6.1

8 years ago

1.7.0

8 years ago

1.6.0

9 years ago

1.5.2

9 years ago

1.5.1

9 years ago

1.5.0

9 years ago

1.4.0

9 years ago

1.3.1

9 years ago

1.3.0

9 years ago

1.2.2

10 years ago

1.2.1

10 years ago

1.2.0

10 years ago

1.1.0

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago