forked from qualitybath/parcel-plugin-run-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (58 loc) · 1.93 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
const path = require('path');
const execa = require('execa');
const chalk = require('chalk').default;
const portfinder = require('portfinder');
module.exports = function(bundler) {
// we only want to run if we're in watch mode and target is set to node
if (bundler.options.watch !== true || bundler.options.target !== 'node') return;
const { outDir, outFile } = bundler.options;
let server;
let starting = false;
let lastBundledHash = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', data => {
if (data.trim() === 'rs') {
restartServer();
}
});
bundler.on('bundled', rootBundle => {
const bundleHash = rootBundle.getHash();
if (bundleHash === lastBundledHash) {
return console.log(chalk.magenta.bold(`🚽 Bundle hasn't been changed`));
}
lastBundledHash = bundleHash;
restartServer();
});
function restartServer() {
if (starting) {
return;
}
starting = true;
if (server) {
console.log(chalk.magenta.bold(`🚽 Killing running server`));
server.once('exit', () => {
console.log(chalk.magenta.bold(`🚽 Running server successfully killed`));
startServer();
});
process.kill(server.pid);
return;
}
startServer();
}
async function startServer() {
if (server) {
throw new Error('trying to start a server when one is already running');
}
const entryPoint = path.join(outDir, outFile);
const inspectPort = await portfinder.getPortPromise({ port: 9229, stopPort: 9239 });
console.log(chalk.magenta.bold(`🚽 Starting server at: \`node ${entryPoint}\``));
server = execa('node', [`--inspect=${inspectPort}`, entryPoint]);
console.log(chalk.magenta.bold(`🚽 Started server: PID ${server.pid}`));
server.once('exit', () => {
server = undefined;
});
server.stdout.pipe(process.stdout);
server.stderr.pipe(process.stderr);
starting = false;
}
};