如何在繁重的任务中保持服务器监听运行?

时间:2021-11-28 20:54:38

I have a HTTP server I'm running as part of one Grunt task. The listen method is asynchronous (as is most Node.js code), so immediately after the Grunt task has called the method it finishes execution and thus closes the server.

我有一个HTTP服务器,作为一个繁重任务的一部分。侦听方法是异步的(与大多数节点一样)。因此,在Grunt任务调用完该方法后,它将立即完成执行,从而关闭服务器。

grunt.registerTask('serveProxy', 'Start the proxy to the various servers', function() {
    var server = http.createServer(function(req, res) {
        // ...
    });
    server.listen(80);
});

How can I keep this running or perhaps make the method block so it doesn't return?

如何保持这个运行,或者使方法块不返回?

1 个解决方案

#1


3  

The solution was to instruct Grunt to wait as per the documentation by telling Grunt this is an asynchronous method and using a callback to indicate when we are done.

解决方案是指示Grunt在文档中通过告诉Grunt这是一个异步方法,并使用回调来指示我们什么时候完成。

grunt.registerTask('serveProxy', 'Start the proxy to the various servers', function() {
    var done = this.async();
    var server = http.createServer(function(req, res) {
        // ...
    });
    server.listen(80);
});

#1


3  

The solution was to instruct Grunt to wait as per the documentation by telling Grunt this is an asynchronous method and using a callback to indicate when we are done.

解决方案是指示Grunt在文档中通过告诉Grunt这是一个异步方法,并使用回调来指示我们什么时候完成。

grunt.registerTask('serveProxy', 'Start the proxy to the various servers', function() {
    var done = this.async();
    var server = http.createServer(function(req, res) {
        // ...
    });
    server.listen(80);
});