npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@jsdevtools/ez-spawn

v3.0.4

Published

Simple, consistent sync or async process spawning

Downloads

204,228

Readme

EZ Spawn

Simple, consistent process spawning

Cross-Platform Compatibility Build Status

Coverage Status Dependencies

npm License Buy us a tree

Features

  • Flexible input parameters Pass the program and arguments as a single string, an array of strings, or as separate parameters.

  • Pick your async syntax Supports Promises, async/await, or callbacks.

  • Simple, consistent error handling Non-zero exit codes are treated just like any other error. See Error Handling for more details.

  • String output by default stdout and stderr output is automatically decoded as UTF-8 text by default. You can set the encoding option for a different encoding, or even raw binary buffers.

  • Windows Support Excellent Windows support, thanks to cross-spawn.

Related Projects

  • chai-exec - Chai assertion plugin for testing CLIs

Examples

const ezSpawn = require('@jsdevtools/ez-spawn');

// These are all identical
ezSpawn.sync(`git commit -am "Fixed a bug"`);           // Pass program and args as a string
ezSpawn.sync("git", "commit", "-am", "Fixed a bug");    // Pass program and args as separate params
ezSpawn.sync(["git", "commit", "-am", "Fixed a bug"]);  // Pass program and args as an array
ezSpawn.sync("git", ["commit", "-am", "Fixed a bug"]);  // Pass program as a string and args as an array

// Make a synchronous call
let process = ezSpawn.sync(`git commit -am "Fixed a bug"`);
console.log(process.stdout);

//Make an asynchronous call, using async/await syntax
let process = await ezSpawn.async(`git commit -am "Fixed a bug"`);
console.log(process.stdout);

//Make an asynchronous call, using callback syntax
ezSpawn.async(`git commit -am "Fixed a bug"`, (err, process) => {
  console.log(process.stdout);
});

//Make an asynchronous call, using Promise syntax
ezSpawn.async(`git commit -am "Fixed a bug"`)
  .then((process) => {
    console.log(process.stdout);
  });

Installation

Install using npm:

npm install @jsdevtools/ez-spawn

Then require it in your code:

// Require the whole package
const ezSpawn = require("@jsdevtools/ez-spawn");

// Or require "sync" or "async" directly
const ezSpawnSync = require("@jsdevtools/ez-spawn").sync;
const ezSpawnAsync = require("@jsdevtools/ez-spawn").async;

API

ezSpawn.sync(command, [...arguments], [options])

Synchronously spawns a process. This function returns when the proecess exits.

  • The command and arguments parameters can be passed as a single space-separated string, or as an array of strings, or as separate parameters.

  • The options object is optional.

  • Returns a Process object

ezSpawn.async(command, [...arguments], [options], [callback])

Asynchronously spawns a process. The Promise resolves (or the callback is called) when the process exits.

  • The command and arguments parameters can be passed as a single space-separated string, or as an array of strings, or as separate parameters.

  • The options object is optional.

  • If a callback is provided, then it will be called when the process exits. The first is either an Error or null. The second parameter is a Process object.

  • If no callback is provided, then a Promise is returned. It will resolve with a Process object when the process exits.

Options object

ezSpawn.async() and ezSpawn.sync() both accept an optional options object that closely mirrors the options parameter of Node's spawn, exec, spawnSync, and execSync functions.

  • cwd (string) The current working directory of the child process.

  • env (Object) Environment variable key-value pairs.

  • argv0 (string) Explicitly set the value of argv[0] sent to the child process. This will be set to command if not specified.

  • stdio (Array or string) The child process's stdio configuration (see options.stdio).

  • input (string, Buffer, TypedArray, or DataView) The value which will be passed as stdin to the spawned process. Supplying this value will override stdio[0].

  • uid (number) Sets the user identity of the process.

  • gid (number) Sets the group identity of the process.

  • timeout (number) The maximum amount of time (in milliseconds) the process is allowed to run.

  • killSignal (string or integer) The signal value to be used when the spawned process will be killed. Defaults to "SIGTERM".

  • maxBuffer (number) The largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated.

  • encoding (string) The encoding used for all stdio inputs and outputs. Defaults to "utf8". Set to "buffer" for raw binary output.

  • shell (boolean or string) If true, then command will be run inside of a shell. Uses "/bin/sh" on UNIX, and process.env.ComSpec on Windows. A different shell can be specified as a string.

  • windowsVerbatimArguments (boolean) No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to true automatically when shell is "CMD".

  • windowsHide (boolean) Hide the subprocess console window that would normally be created on Windows systems.

Process object

ezSpawn.async() and ezSpawn.sync() both return a Process object that closely mirrors the object returned by Node's spawnSync function.

  • command (string) The command that was used to spawn the process.

  • args (array of strings) The command-line arguments that were passed to the process.

  • pid (number) The numeric process ID assigned by the operating system.

  • stdout (string or Buffer) The process's standard output. This is the same value as output[1].

  • stderr (string or Buffer) The process's error output. This is the same value as output[2].

  • output (array of strings or Buffers) The process's stdio [stdin, stdout, stderr].

  • status (number) The process's status code (a.k.a. "exit code").

  • signal (string or null) The signal used to kill the process, if the process was killed by a signal.

  • toString() Returns the command and args as a single string. Useful for console logging.

Error Handling

All sorts of errors can occur when spawning processes. Node's built-in spawn and spawnSync functions handle different types of errors in different ways. Sometimes they throw the error, somtimes they emit an "error" event, and sometimes they return an object with an error property. They also don't treat non-zero exit codes as errors. So it's up to you to handle all these different types of errors, and check the exit code too.

EZ Spawn simplifies things by treating all errors the same. If any error occurs, or if the process exits with a non-zero exit code, then an error is thrown. The error will have all the same properties as the Process object, such as status, stderr, signal, etc.

try {
  let process = ezSpawn.sync(`git commit -am "Fixed a bug"`, { throwOnError: true });
  console.log("Everything worked great!", process.stdout);
}
catch (error) {
  console.error("Something went wrong!", error.status, error.stderr);
}

Contributing

Contributions, enhancements, and bug-fixes are welcome! Open an issue on GitHub and submit a pull request.

Building/Testing

To build/test the project locally on your computer:

  1. Clone this repo git clone hhttps://github.com/JS-DevTools/ez-spawn.git

  2. Install dependencies npm install

  3. Run the tests npm test

License

EZ Spawn is 100% free and open-source, under the MIT license. Use it however you want.

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

Big Thanks To

Thanks to these awesome companies for their support of Open Source developers ❤

Travis CI SauceLabs Coveralls