Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

spawn-rx

Package Overview
Dependencies
Maintainers
1
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

spawn-rx

An Rx-version of child_process.spawn

  • 5.1.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
12K
decreased by-11.06%
Maintainers
1
Weekly downloads
 
Created
Source

spawn-rx: A better version of spawn

Linux/OSXWindows
Build StatusBuild status

spawn-rx is a package that adds an Observable as well as a Promise version of the child_process.spawn API, and fixes some deficiencies in spawn that come up especially on Windows. For example:

  • spawn searches PATH on POSIX platforms but will not on Windows, you need to provide an exact path. spawn-rx makes Windows act like other platforms.

  • On Windows, {detached: true} doesn't actually create a process group properly. spawn-rx provides a spawnDetached method that allows you to spawn a detached process and kill the entire process group if needed.

  • POSIX platforms allow you to directly execute scripts that have a shebang at the top of the file, whereas Windows can only natively spawn EXE files, which makes executing npm binaries annoying. spawn-rx automatically rewrites your cmd and args parameters for CMD scripts, PowerShell scripts, and node.js files.

Examples

spawn-as-promise:

// Will run down path to find C:\Windows\System32\wmic.exe, whereas normal 
// 'spawn' would require an absolute path.
spawnPromise('wmic', [])
  .then((result) => console.log(result));

Handle failed processes as errors:

try {
  await spawnPromise('exit', ['-1']);
} catch (e) {
  console.log("Processes that return non-zero exit codes throw")
}

Kill running process trees:

let disp = spawnDetached('takesALongTime', []).subscribe();
await Promise.delay(1000);

// Kill the process and its children by unsubscribing.
disp.dispose();

Stream process output:

spawn('ls', ['-r'])
  .subscribe(
    (x) => console.log(x), 
    (e) => console.log("Process exited with an error"));

Execute scripts:

// Executes ./node_modules/.bin/uuid.cmd on Windows if invoked via `npm run`
let result = await spawnPromise('uuid');

What's Jobber?

Jobber is a Windows executable that will execute a command in a process group, and if signaled via a named pipe, will terminate that process group. It's used in the implementation of spawnDetached. Jobber was written by me, and its license is the same as spawn-rx, it is not a third-party dependency.

Spawn output

By default spawn will merge stdout and stderr into the returned observable. You can exclude one or the other by passing ignore in the stdio option of spawn.

Alternatively if you call it with { split: true } option, the observable output will be an object { source: 'stdout', text: '...' } so you can distinguish the outputs.

Stdin support

If you provide an Observable<string> in opts.stdin, it'll be subscribed upon and fed into the child process stdin. Its completion will terminate stdin stream.

Methods

/**
 * Spawns a process attached as a child of the current process.
 *
 * @param  {string} exe               The executable to run
 * @param  {string[]} params     The parameters to pass to the child
 * @param  {SpawnOptions & SpawnRxExtras} opts              Options to pass to spawn.
 *
 * @return {Observable<OutputLine>}       Returns an Observable that when subscribed
 *                                    to, will create a child process. The
 *                                    process output will be streamed to this
 *                                    Observable, and if unsubscribed from, the
 *                                    process will be terminated early. If the
 *                                    process terminates with a non-zero value,
 *                                    the Observable will terminate with onError.
 */
function spawn(
  exe: string,
  params: string[],
  opts: SpawnOptions & SpawnRxExtras & { split: true }
): Observable<OutputLine>;

function spawn(
  exe: string,
  params: string[],
  opts?: SpawnOptions & SpawnRxExtras & { split: false | undefined }
): Observable<string>;

/**
 * Spawns a process but detached from the current process. The process is put
 * into its own Process Group.
 *
 * @param  {string} exe               The executable to run
 * @param  {string[]} params     The parameters to pass to the child
 * @param  {SpawnOptions & SpawnRxExtras} opts              Options to pass to spawn.
 *
 * @return {Observable<OutputLine>}       Returns an Observable that when subscribed
 *                                    to, will create a detached process. The
 *                                    process output will be streamed to this
 *                                    Observable, and if unsubscribed from, the
 *                                    process will be terminated early. If the
 *                                    process terminates with a non-zero value,
 *                                    the Observable will terminate with onError.
 */
function spawnDetached(
  exe: string,
  params: string[],
  opts: SpawnOptions & SpawnRxExtras & { split: true }
): Observable<OutputLine>;

function spawnDetached(
  exe: string,
  params: string[],
  opts?: SpawnOptions & SpawnRxExtras & { split: false | undefined }
): Observable<string>;

/**
 * Spawns a process as a child process.
 *
 * @param  {string} exe               The executable to run
 * @param  {string[]} params     The parameters to pass to the child
 * @param  {SpawnOptions & SpawnRxExtras} opts              Options to pass to spawn.
 *
 * @return {Promise<[string, string]>}       Returns a Promise that represents a child
 *                                 process. The value returned is the process
 *                                 output. If the process terminates with a
 *                                 non-zero value, the Promise will resolve with
 *                                 an Error.
 */
function spawnPromise(
  exe: string,
  params: string[],
  opts: SpawnOptions & SpawnRxExtras & { split: true }
): Promise<[string, string]>;

function spawnPromise(
  exe: string,
  params: string[],
  opts?: SpawnOptions & SpawnRxExtras
): Promise<string>;

/**
 * Spawns a process but detached from the current process. The process is put
 * into its own Process Group.
 *
 * @param  {string} exe               The executable to run
 * @param  {string[]} params     The parameters to pass to the child
 * @param  {SpawnOptions & SpawnRxExtras} opts              Options to pass to spawn.
 *
 * @return {Promise<[string, string]>}       Returns a Promise that represents a detached
 *                                 process. The value returned is the process
 *                                 output. If the process terminates with a
 *                                 non-zero value, the Promise will resolve with
 *                                 an Error.
 */
function spawnDetachedPromise(
  exe: string,
  params: string[],
  opts: SpawnOptions & SpawnRxExtras & { split: true }
): Promise<[string, string]>;

function spawnDetachedPromise(
  exe: string,
  params: string[],
  opts?: SpawnOptions & SpawnRxExtras
): Promise<string>;

/**
 * Finds the actual executable and parameters to run on Windows. This method
 * mimics the POSIX behavior of being able to run scripts as executables by
 * replacing the passed-in executable with the script runner, for PowerShell,
 * CMD, and node scripts.
 *
 * This method also does the work of running down PATH, which spawn on Windows
 * also doesn't do, unlike on POSIX.
 *
 * @param  {string} exe           The executable to run
 * @param  {string[]} args   The arguments to run
 *
 * @return {Object}               The cmd and args to run
 * @property {string} cmd         The command to pass to spawn
 * @property {string[]} args The arguments to pass to spawn
 */
function findActualExecutable(
  exe: string,
  args: string[]
): {
  cmd: string;
  args: string[];
};

Keywords

FAQs

Package last updated on 05 Dec 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc