UNPKG

1.99 kBJavaScriptView Raw
1/*eslint-env es6*/
2
3const http = require('http');
4const path = require('path');
5const serveFiles = require('serve-files');
6const spawn = require('child_process').spawn;
7
8if (!process.argv[2]) {
9 process.stdout.write(`USAGE: node ${path.basename(module.filename)} [example_path]\n`);
10 process.exit(0);
11}
12
13const root = process.cwd();
14const port = 8000;
15const host = null;
16const examplePath = process.argv[2];
17const phantomPath = require('phantomjs-prebuilt').path;
18
19const server = http.createServer(serveFiles.createFileResponseHandler({
20 documentRoot: root,
21 followSymbolicLinks: false,
22 cacheTimeInSeconds: 3600
23}));
24
25server.listen(port, host, null, function() {
26 const childProcess = spawn(phantomPath, ['--ssl-protocol=any', '--ignore-ssl-errors=true', path.join(__dirname, '..', 'bin', 'check-example.js'), 'http://localhost:8000/' + examplePath]);
27 childProcess.stdout.pipe(process.stdout);
28 childProcess.stderr.pipe(process.stderr);
29 process.stdin.pipe(childProcess.stdin);
30
31 childProcess.on('error', function(err) {
32 process.stderr.write(`Error executing phantom on ${phantomPath}\n`);
33 process.stderr.write(err.stack + '\n');
34 process.exit(1);
35 });
36
37 childProcess.on('exit', function(code) {
38 process.exit(code);
39 });
40
41});
42
43// Keep track of connections, to enforce killing them when server must be stopped.
44var connections = {};
45server.on('connection', function(socket) {
46 socket._cid = process.hrtime();
47 connections[socket._cid] = socket;
48
49 socket.on('end', function() {
50 delete connections[this._cid];
51 });
52});
53
54['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'].forEach(signal => {
55 process.once(signal, () => {
56 process.stdout.write(`Got ${signal}, stopping...\n`),
57 server.close(() => {
58 process.stdout.write('Stopped.\n');
59 process.exit(0);
60 });
61
62 Object.keys(connections).forEach(cid => connections[cid].destroy());
63 });
64});