forked from M-Zuber/npm-watch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatch-package.js
More file actions
92 lines (78 loc) · 2.36 KB
/
watch-package.js
File metadata and controls
92 lines (78 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
var path = require('path')
var spawn = require('child_process').spawn
var through = require('through2')
var npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
var nodemon = process.platform === 'win32' ? 'nodemon.cmd' : 'nodemon';
module.exports = function watchPackage (pkgDir, exit) {
var pkg = require(path.join(pkgDir, 'package.json'))
var processes = {}
if (typeof pkg.watch !== 'object') {
die('No "watch" config in package.json')
}
// send 'rs' commands to the right proc
var stdin = through(function (line, _, callback) {
line = line.toString()
var match = line.match(/^rs\s+(\w+)/)
if (!match) {
console.log('Unrecognized input:', line)
return callback()
}
var proc = processes[match[1]]
if (!proc) {
console.log('Couldn\'t find process:', match[1])
return callback()
}
proc.stdin.write('rs\n')
callback()
})
stdin.stderr = through()
stdin.stdout = through()
Object.keys(pkg.watch).forEach(function (script) {
if (!pkg.scripts[script]) {
die('No such script "' + script + '"', 2)
}
var exec = [npm, 'run', script].join(' ')
var patterns = null
var extensions = null
if (typeof pkg.watch[script] === 'object' && !Array.isArray(pkg.watch[script])) {
patterns = pkg.watch[script].patterns
extensions = pkg.watch[script].extensions
} else {
patterns = pkg.watch[script]
}
patterns = [].concat(patterns).map(function (pattern) {
return ['--watch', pattern]
}).reduce(function (a, b) {
return a.concat(b)
})
var args = extensions ? ['--ext', extensions] : []
args = args.concat(patterns)
args = args.concat(['--exec', exec])
console.log(args);
var proc = processes[script] = spawn(nodemon, args, {
env: process.env,
cwd: pkgDir,
stdio: 'pipe'
})
proc.stdout.pipe(prefixer('[' + script + ']')).pipe(stdin.stdout)
proc.stderr.pipe(prefixer('[' + script + ']')).pipe(stdin.stderr)
})
return stdin
function die (message, code) {
stdin.stderr.write(message)
stdin.end()
stdin.stderr.end()
stdin.stdout.end()
exit(code || 1)
}
}
function prefixer (prefix) {
return through(function (line, _, callback) {
line = line.toString()
if (!line.match('to restart at any time')) {
this.push(prefix + ' ' + line)
}
callback()
})
}