0

I have a requirement that i want to run my task after booting a http server.

But i cannot check whether the server is booted.

Instead,i used a setTimeout function to assume the server is booted with 2 seconds interval.

Could anybody,who knows a better solution,help me?

Great thanks!

My code is as follows:

// main.js
function exec(command) {

    var defer = q.defer();
    var child = childProcess.exec(command, function (err, stdout, stderr) {
        if (err) {
            return defer.reject(err);
        }
    });

    child.stdout.pipe(process.stdout);

    // TODO: find another graceful way to check child process ends
    setTimeout(function () {
        defer.resolve();
    }, 2000);

    return defer.promise;

}

exec('"' + process.execPath + '" app.js')
    .then(function () {
        // my task here;
        console.log('my task')
    });

// app.js
var http = require('http'),
    server;

server = http.createServer(function (req, res) {
    // serve html;
    res.end('hello world');
});

server.listen(9999);

// run
$> node main.js

1 Answers1

0

A good solution would be to try to connect to the webserver until it responds. Since you're using Q, you can take a look at the code from this answer, which enables you to retry an operation until it succeeds.

function retry(operation, delay) {
    return operation().catch(function(reason) {
        // Note: I replaced delay * 2 by delay, it will be better in your case
        return Q.delay(delay).then(retry.bind(null, operation, delay));
    });
}

Then you could do something like

startMyWebServer()
.then (function () {
    return retry(connectToWebServer, 500).timeout(10000);
})
.then(function () {
    console.log("Webserver ready")
})
.catch(function (err) {
    console.log("Unable to contact webserver")
});

The call to retry will retry to connect to the webserver if the previous connection failed, with a delay of 500ms. If after 10s it didn't succeed, the promise will be rejected.

The connectToWebServer function should be a function that tries to connect to your webserver and returns a promise, i.e. something like

function connectToWebServer() {
    var d = q.defer();
    request('http://your-ip:your-port', function (err, res) {
        if (err || res.statusCode != 200) {
           return d.reject("Error : "+(err || "status code "+res.statusCode));
        }
        d.resolve();
    }
    return d.promise;
}
Community
  • 1
  • 1
christophetd
  • 3,834
  • 20
  • 33