• Stars
    star
    136
  • Rank 267,670 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Observable and Promise versions of child_process.spawn

spawn-rx: A better version of spawn

Linux/OSX Windows
Build Status Build 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.

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  {Array<string>} params     The parameters to pass to the child
 * @param  {Object} opts              Options to pass to spawn.
 *
 * @return {Observable<string>}       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, params=[], opts=null)
/**
 * Spawns a process but detached from the current process. The process is put 
 * into its own Process Group that can be killed by unsubscribing from the 
 * return Observable.
 * 
 * @param  {string} exe               The executable to run
 * @param  {Array<string>} params     The parameters to pass to the child
 * @param  {Object} opts              Options to pass to spawn.
 *
 * @return {Observable<string>}       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, params, opts=null)
/**
 * Spawns a process as a child process.
 * 
 * @param  {string} exe               The executable to run
 * @param  {Array<string>} params     The parameters to pass to the child
 * @param  {Object} opts              Options to pass to spawn.
 *
 * @return {Promise<string>}       Returns an 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, params, opts=null)
/**
 * 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  {Array<string>} params     The parameters to pass to the child
 * @param  {Object} opts              Options to pass to spawn.
 *
 * @return {Promise<string>}       Returns an 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, params, opts=null)
/**
 * 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  {Array<string>} args   The arguments to run
 *
 * @return {Object}               The cmd and args to run
 * @property {string} cmd         The command to pass to spawn
 * @property {Array<string>} args The arguments to pass to spawn
 */
function findActualExecutable(exe, args)

More Repositories

1

ModernHttpClient

HttpClient implementations that use platform-native HTTP clients for 🚀
C#
661
star
2

SassAndCoffee

SassAndCoffee adds support in ASP.NET MVC to (you guessed it!) Sass/SCSS and CoffeeScript
JavaScript
199
star
3

starter-mobile

Starter project for Mobile projects at GitHub
C#
156
star
4

xvfb-maybe

Run an executable under xvfb-run, but only when needed
JavaScript
133
star
5

grunt-build-atom-shell

Grunt task to build Electron and rebuild node modules
CoffeeScript
122
star
6

LinqToAwait

A Task-based LINQ designed to work with async/await
C#
113
star
7

node-system-idle-time

Node module to get system-idle-time, fork with Linux support
C++
101
star
8

XamarinEvolve2014

App Repo for "Building Apps the GitHub Way"
C#
91
star
9

SaveAllTheTime

SaveAllTheTime makes it so you never commit files to Git without saving ever again
C#
73
star
10

AkavacheExplorer

A utility to poke around in Akavache caches
C#
68
star
11

squirrel-flutter

Build installers for your Flutter applications with Squirrel
Dart
57
star
12

PerMonitorDpi

Enable Windows 8.1+ Per-Monitor DPI support for Desktop WPF Apps
C#
51
star
13

ssh-agent-relay

Make your WSL installation use your Windows SSH Agent
Shell
37
star
14

atom-twitch

Atom plugin for Live Coding
JavaScript
34
star
15

RunscopeEverything

An Xposed module that will rewrite all web requests on Android and point them to Runscope
Java
27
star
16

midi-mixer-wavexlr

A Wave Link plugin for MIDI Mixer
JavaScript
23
star
17

typechat-cli

A command-line wrapper around TypeChat - invoke OpenAI or Ollama with a specific JS schema
TypeScript
21
star
18

commands

Commands - a React Hooks library for writing async code
TypeScript
21
star
19

ReactiveUI.Sample

Sample 3.0â„¢
C#
20
star
20

starter-sample

ReactiveUI + Akavache + Splat Sample
C#
20
star
21

BigNerdIOS-MonoDevelop

Big Nerd Ranch's iOS book, but in MonoDevelop
C#
18
star
22

XamarinRxDemo

Java
14
star
23

xamarin-dep-rebuild

A hack to rebuild all of the libraries we use in Xamarin apps
Shell
13
star
24

sirene

Dart
13
star
25

CaliburnMicro

My hacks on top of Caliburn Micro
C#
12
star
26

OneTrueCSharpStyle

The One True C# Style
12
star
27

electron-vue-sample

Vue 2.0 single-file components + electron-compile
JavaScript
12
star
28

libcef

Mirror of CEF3
C++
12
star
29

reactiveui

This Repo Is Dead, you want https://github.com/reactiveui/reactiveui
C#
11
star
30

OkHttp-Xamarin

Xamarin bindings for squareup/okhttp
C#
11
star
31

aluqard

GraphQL + Flutter Hooks
Dart
11
star
32

when

Observe JavaScript objects with RxJS
TypeScript
10
star
33

trickline

A Fucking Fast Slack Data Model
TypeScript
10
star
34

peasant

The simplest CI server that could possibly work
C#
9
star
35

PhotoDispatcher

A site to send Eye-Fi photos to multiple sites via an iPhone site
Ruby
8
star
36

Shotclock

A NuGet package to encourage you to create small commits
C#
8
star
37

rxjs-serial-subscription

RxJS 5.x version of SerialSubscription
JavaScript
8
star
38

commands-compose

Commands - a Jetpack Compose library for writing async events
Kotlin
7
star
39

RxUIInterfaceToVM

Hack code to use Roslyn + Mustache to codegen ReactiveUI ViewModels
C#
7
star
40

github-emoji-switcher

A Chrome Extension that switches old-and-busted Apple Emojis into new and ✨ Shiny ✨ Hangouts emoji! 🚀
JavaScript
7
star
41

vcachefs

A media caching filesystem written using FUSE
C
6
star
42

blogstrap

A GitHub Pages-based starter template for your blog
JavaScript
6
star
43

Shroom

Java
6
star
44

Tasks

A Ruby library to parse Taskpaper and other todo list formats
Ruby
5
star
45

component-store-nupkg-builder

A set of scripts to build Xamarin Component Store shim packages
Ruby
5
star
46

vue-pwa-typescript

Vue 2.5's PWA template using the new Babel 7.x TypeScript preset
JavaScript
5
star
47

AFNetworking-Xamarin

Xamarin AFNetworking binding, based on thefactory/AFNetworking-Sharp
C#
5
star
48

GistForVS

A VSIX extension that adds the ability to create Gists from Visual Studio
C#
5
star
49

InstallQueuer

A Windows app to queue up several MSIs to install in the background
C#
5
star
50

rdio-play-here

List all of your running machines and make Rdio play on any of them
JavaScript
5
star
51

zapped

A small utility to add XServer's Zap to Windows and OS X
C
4
star
52

chromeapp-materialdesign

Demo for Chrome App + Material Design + AngularJS
JavaScript
4
star
53

RxUIBlog

All of the RxUI blog posts and some tooling to create a PDF / ePub version
4
star
54

GameShare

A website to organize small groups to borrow video games
Ruby
4
star
55

yikes

An automatic way to convert videos and put them on your iPod
C
4
star
56

camploco

Camp Lakota Merit Badge Site
JavaScript
4
star
57

windows-terminal-theme-sync

VS Code extension to sync color themes with Windows Terminal
TypeScript
3
star
58

mongodbfs

A FUSE filesystem over MongoDB's GridFS
C
3
star
59

ModernCommonLogging

Common.Logging for .NET 4.0 / SL4 / WP7
3
star
60

pinguine-wsl

Utility to improve WSL
3
star
61

ReactiveXaml

This project has been renamed to ReactiveUI - check it out below!
3
star
62

poolsuite-androidtv

The literal bare minimum to get poolsuite onto my heckin TV
Dart
3
star
63

desktop-analytics

Common Analytics and Reporting
C#
3
star
64

foo

3
star
65

slack-all-langs

Sample code to post a message in every language to Slack
JavaScript
3
star
66

Estelle

A command-line music reorganization app
C++
3
star
67

groupme-ios-sdk

A GroupMe client library for iOS devices
Objective-C
3
star
68

lithium

A Reactive API for Home Assistant
TypeScript
2
star
69

xpaulbettsx.github.com

Ruby
2
star
70

electron-sample

Sample app using the CLI
CoffeeScript
2
star
71

play-wp8

Dummy project, ignore this
C#
2
star
72

NSync

NSync
2
star
73

gformat

A GNOME disk formatting utility I wrote a billion years ago
C
2
star
74

password2

password with offline support
JavaScript
2
star
75

channels-web

Web client for Channels
TypeScript
2
star
76

ReactiveUI_5.99.3-beta-WP8

Repro repo for issue with the ReactiveUI 5.99.3-beta NuGet package
C#
2
star
77

RxUI_BindingFailure

Demonstrates the combobox selected item binding failure
C#
2
star
78

Istoria

My life in code
Ruby
2
star
79

HerokuClickonceTest

This is not a thing.
Ruby
2
star
80

Malcolm

An application that helps you be more productive
C#
2
star
81

LeeMe.Mobile

So you can be about that life.
C#
2
star
82

saveallthetime-atom

SaveAllTheTime makes it so you never commit files to Git without saving ever again
CoffeeScript
1
star
83

OBSKeyboardMute

Mute your clackety keyboard in OBS
C#
1
star
84

glibc-legal-notice

An npm package whose license metadata describes your linking to glibc
1
star
85

ShroomServer

1
star
86

marie

keep your house clutter-free!
TypeScript
1
star
87

esdoc-plugin-async-to-sync

Auto-documents your sync methods using the async versions
JavaScript
1
star
88

when-flutter

Dart
1
star
89

flutter-actions

Action Hooks, a Flutter Hook for building asynchronous commands
Dart
1
star
90

debug-electron

It's debug, but electron-friendly
JavaScript
1
star
91

timeout-cli

GNU timeout but cross-platform also with missing features
JavaScript
1
star
92

toilet-paper-cheater

it does.
TypeScript
1
star
93

slime

An Atom plugin to communicate with your inferiors (processes)
CoffeeScript
1
star
94

symlink-test

Ignore me
1
star