forked from gimm/gulp-express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
111 lines (100 loc) · 3.02 KB
/
index.js
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* Created by Gimm on 7/17/14.
*/
var util = require('util'),
path = require('path'),
child_process = require('child_process'),
merge = require('deepmerge'),
tinylr = require('tiny-lr'),
es = require('event-stream'),
debug = require('debug')('gulp:express');
module.exports = (function () {
var node = null,
defaults = {
args: ['app.js'],
options: {
cwd: undefined,
lr: {
port: 35729
}
}
};
defaults.options.env = process.env;
defaults.options.env.NODE_ENV = 'development';
var lr;
var livereload = {
start: function (livereloadOptions) {
if (lr == undefined) {
lr = tinylr(livereloadOptions);
}
lr.listen(livereloadOptions.port);
},
reload: function (filename) {
if (lr != undefined) {
lr.changed({
body: {
files: [filename]
}
});
} else {
debug('tinylr not started');
node && node.kill();
}
}
};
var listener = {
processExit: function (code, sig) {
debug('Main process exited with [code => %s | sig => %s]', code, sig);
node && node.kill();
},
nodeExit: function (code, sig) {
debug('Node process exited with [code => %s | sig => %s]', code, sig);
if (lr != undefined) {
lr.close();
}
},
logData: function (data) {
debug(data.trim());
}
};
return {
run: function (args, options) {
args = (util.isArray(args) && args.length) ? args : defaults.args;
options = merge(defaults.options, options || {});
if (node) { // Stop
node.kill('SIGKILL');
node = undefined;
process.removeListener('exit', listener.processExit);
} else {
livereload.start(options.lr);
}
node = child_process.spawn('node', args, options);
if (node.stdout) {
node.stdout.setEncoding('utf8');
node.stdout.on('data', listener.logData);
}
if (node.stderr) {
node.stderr.setEncoding('utf8');
node.stderr.on('data', listener.logData);
}
node.on('exit', listener.nodeExit);
process.on('exit', listener.processExit);
return node;
},
stop: function () {
if (node) {
node.kill('SIGKILL');
node = undefined;
}
},
notify: function (event) {
if(event && event.path){
livereload.reload(path.relative(__dirname, event.path));
}
return es.map(function(file, done) {
livereload.reload(path.relative(__dirname, file.path));
done(null, file);
});
}
};
})();