UNPKG

1.36 kBJavaScriptView Raw
1const spawn = require('child_process').spawn;
2const treeKill = require('tree-kill');
3
4class Spawn {
5 constructor(command) {
6
7 this.subscribers = {}
8
9 // linux
10 this.child = spawn('/bin/sh',
11 ['-c', command],
12 {
13 cwd: null,
14 env: null,
15 windowsVerbatimArguments: false
16 })
17
18 // TODO windows
19 // this.child = require('child_process').spawn(
20 // 'cmd.exe',
21 // ['/s', '/c', command],
22 // {
23 // cwd: null,
24 // env: null,
25 // windowsVerbatimArguments: true
26 // }
27 // );
28
29
30 this.child.stdout.on('data', (str) => {
31 this.dispatch('data', '' + str)
32 })
33
34 this.child.stderr.on('data', (str) => {
35 this.dispatch('data', '' + str)
36 })
37
38 this.child.on('error', (err) => {
39 this.dispatch('error', `command exec error: ${err.message}`)
40 treeKill(this.pid)
41 })
42
43 this.child.on('close', (code) => {
44 if (!code) {
45 this.dispatch('close', '')
46 } else {
47 this.dispatch('error', `command close error: ${code}`)
48 }
49 treeKill(this.pid)
50 })
51
52 this.pid = this.child.pid
53 }
54
55
56 /**
57 * event name:
58 * data, error, success
59 */
60 on(event, func) {
61 this.subscribers[event] = func;
62 }
63
64
65 dispatch(event, args) {
66 this.subscribers[event] && this.subscribers[event](args)
67 }
68}
69
70module.exports = Spawn