0

Need gulp 4.0.2 task to wait for express 4.17.1 server to start, then open a browser.

Here's what I have that works (but I think it's pretty old school)...

// Start server in development or test mode
gulp.task('start:server', () => {
  process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  config = require(`./${serverPath}/config/environment`).default;
  nodemon(`--inspect --trace-deprecation --trace-warnings -w ${serverPath} ${serverPath}`)
    .on('log', onServerLog);
});

// Run nodemon with debugging (server/config/express.js runs webpack.make.js)
gulp.task('serve',
  gulp.series(
    gulp.parallel('eslint', 'eslint:tests', 'client:inject:scss', 'dist:client:assets:fonts', 'env:common'),
    gulp.parallel('start:server', 'start:client'),
    'watch'
  )
);

// Perform HTTP GET to check for app readiness
function checkAppReady(cb) {
  let options = {
    host: 'localhost',
    port: config.port
  };
  http.get(options, () => cb(true))
    .on('error', () => cb(false));
}

// Check every 250ms until app server is ready
function whenServerReady(cb) {
  let serverReady = false;
  let appReadyInterval = setInterval(() =>
    checkAppReady(ready => {
      if(!ready || serverReady) {
        return;
      }
      clearInterval(appReadyInterval);
      serverReady = true;
      cb();
    }),
  250);
}

// Wait until server is responding then open browser on client to our starting page
gulp.task('start:client', done => {
  whenServerReady(() => {
    opn(`http://localhost:${config.browserSyncPort}`/*, {app: 'google chrome'}*/);
    done();
  });
});

While this works well, I'm wondering if there's a more streamlined way to accomplish the same thing. The last StackOverflow post on the subject is more than 3 years old.

nstuyvesant
  • 1,392
  • 2
  • 18
  • 43
  • You could rewrite everything to work with promises but the difference would be largely syntactic. The overall polling paradigm would be more or less the same. IMHO, a rewrite is not worth the effort unless you go for some alternative to polling. Not too sure what that might be. – Roamer-1888 Aug 31 '19 at 12:10
  • Does [this provide any clues](https://stackoverflow.com/q/24600052/3478010)? – Roamer-1888 Aug 31 '19 at 12:14
  • 1
    Thanks Roamer-1888. Was wondering if there might be something I could do based on monitoring an emitted event. – nstuyvesant Aug 31 '19 at 15:46

0 Answers0