forked from kriasoft/react-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunServer.js
76 lines (63 loc) · 1.92 KB
/
runServer.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
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import path from 'path';
import cp from 'child_process';
import webpackConfig from './webpack.config';
// Should match the text string used in `src/server.js/server.listen(...)`
const RUNNING_REGEXP = /The server is running at http:\/\/(.*?)\//;
let server;
let pending = true;
const [, serverConfig] = webpackConfig;
const serverPath = path.join(
serverConfig.output.path,
serverConfig.output.filename.replace('[name]', 'server'),
);
// Launch or restart the Node.js server
function runServer() {
return new Promise(resolve => {
function onStdOut(data) {
const time = new Date().toTimeString();
const match = data.toString('utf8').match(RUNNING_REGEXP);
process.stdout.write(time.replace(/.*(\d{2}:\d{2}:\d{2}).*/, '[$1] '));
process.stdout.write(data);
if (match) {
server.host = match[1];
server.stdout.removeListener('data', onStdOut);
server.stdout.on('data', x => process.stdout.write(x));
pending = false;
resolve(server);
}
}
if (server) {
server.kill('SIGTERM');
}
server = cp.spawn('node', [serverPath], {
env: Object.assign({ NODE_ENV: 'development' }, process.env),
silent: false,
});
if (pending) {
server.once('exit', (code, signal) => {
if (pending) {
throw new Error(
`Server terminated unexpectedly with code: ${code} signal: ${signal}`,
);
}
});
}
server.stdout.on('data', onStdOut);
server.stderr.on('data', x => process.stderr.write(x));
return server;
});
}
process.on('exit', () => {
if (server) {
server.kill('SIGTERM');
}
});
export default runServer;