runServer.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * React Starter Kit (https://www.reactstarterkit.com/)
  3. *
  4. * Copyright © 2014-2016 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. import path from 'path';
  10. import cp from 'child_process';
  11. import webpackConfig from './webpack.config';
  12. // Should match the text string used in `src/server.js/server.listen(...)`
  13. const RUNNING_REGEXP = /The server is running at http:\/\/(.*?)\//;
  14. let server;
  15. const { output } = webpackConfig.find(x => x.target === 'node');
  16. const serverPath = path.join(output.path, output.filename);
  17. // Launch or restart the Node.js server
  18. function runServer(cb) {
  19. function onStdOut(data) {
  20. const time = new Date().toTimeString();
  21. const match = data.toString('utf8').match(RUNNING_REGEXP);
  22. process.stdout.write(time.replace(/.*(\d{2}:\d{2}:\d{2}).*/, '[$1] '));
  23. process.stdout.write(data);
  24. if (match) {
  25. server.stdout.removeListener('data', onStdOut);
  26. server.stdout.on('data', x => process.stdout.write(x));
  27. if (cb) {
  28. cb(null, match[1]);
  29. }
  30. }
  31. }
  32. if (server) {
  33. server.kill('SIGTERM');
  34. }
  35. server = cp.spawn('node', [serverPath], {
  36. env: Object.assign({ NODE_ENV: 'development' }, process.env),
  37. silent: false,
  38. });
  39. server.stdout.on('data', onStdOut);
  40. server.stderr.on('data', x => process.stderr.write(x));
  41. }
  42. process.on('exit', () => {
  43. if (server) {
  44. server.kill('SIGTERM');
  45. }
  46. });
  47. export default runServer;