ff-stream-web

git clone git://archive.git.mtrnord.blog/MTRNord/ff-stream-web.git
Log | Files | Refs | README | LICENSE

runServer.js (1910B)


      1 /**
      2  * React Starter Kit (https://www.reactstarterkit.com/)
      3  *
      4  * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
      5  *
      6  * This source code is licensed under the MIT license found in the
      7  * LICENSE.txt file in the root directory of this source tree.
      8  */
      9 
     10 import path from 'path';
     11 import cp from 'child_process';
     12 import webpackConfig from './webpack.config';
     13 
     14 // Should match the text string used in `src/server.js/server.listen(...)`
     15 const RUNNING_REGEXP = /The server is running at http:\/\/(.*?)\//;
     16 
     17 let server;
     18 let pending = true;
     19 const [, serverConfig] = webpackConfig;
     20 const serverPath = path.join(serverConfig.output.path, serverConfig.output.filename);
     21 
     22 // Launch or restart the Node.js server
     23 function runServer() {
     24   return new Promise((resolve) => {
     25     function onStdOut(data) {
     26       const time = new Date().toTimeString();
     27       const match = data.toString('utf8').match(RUNNING_REGEXP);
     28 
     29       process.stdout.write(time.replace(/.*(\d{2}:\d{2}:\d{2}).*/, '[$1] '));
     30       process.stdout.write(data);
     31 
     32       if (match) {
     33         server.host = match[1];
     34         server.stdout.removeListener('data', onStdOut);
     35         server.stdout.on('data', x => process.stdout.write(x));
     36         pending = false;
     37         resolve(server);
     38       }
     39     }
     40 
     41     if (server) {
     42       server.kill('SIGTERM');
     43     }
     44 
     45     server = cp.spawn('node', [serverPath], {
     46       env: Object.assign({ NODE_ENV: 'development' }, process.env),
     47       silent: false,
     48     });
     49 
     50     if (pending) {
     51       server.once('exit', (code, signal) => {
     52         if (pending) {
     53           throw new Error(`Server terminated unexpectedly with code: ${code} signal: ${signal}`);
     54         }
     55       });
     56     }
     57 
     58     server.stdout.on('data', onStdOut);
     59     server.stderr.on('data', x => process.stderr.write(x));
     60 
     61     return server;
     62   });
     63 }
     64 
     65 process.on('exit', () => {
     66   if (server) {
     67     server.kill('SIGTERM');
     68   }
     69 });
     70 
     71 export default runServer;