1 | const spawn = require('child_process').spawn;
|
2 | const treeKill = require('tree-kill');
|
3 |
|
4 | class Spawn {
|
5 | constructor(command) {
|
6 |
|
7 | this.subscribers = {}
|
8 |
|
9 |
|
10 | this.child = spawn('/bin/sh',
|
11 | ['-c', command],
|
12 | {
|
13 | cwd: null,
|
14 | env: null,
|
15 | windowsVerbatimArguments: false
|
16 | })
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
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 |
|
58 |
|
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 |
|
70 | module.exports = Spawn
|