Grunt启动Node Server,然后打开浏览器

kx1ctssn  于 2023-05-22  发布在  Node.js
关注(0)|答案(2)|浏览(120)

我有一个启动服务器的grunt任务:

module.exports = function(grunt){ 
  grunt.registerMultiTask('connect', 'Run a simple Node Server', function(){
    var options = this.options();
    // Tell Grunt this task is asynchronous.
    var done = this.async();
    var server = connect();
    server.use(function(request, response, nxt){
      ...
    });
    server.listen(port);
  });
};

现在我想先用grunt启动这个节点服务器,然后用grunt-open插件打开浏览器。

grunt.task.run(['startServer', 'open']);

但是startServer任务在服务器继续监听时阻塞了打开的任务。我应该做什么来保持这个节点服务器运行,并在服务器启动后打开浏览器?

8yoxcaq7

8yoxcaq71#

我有同样的问题,你和我在Windows环境中工作.我的解决方案是将Web服务器代码放在一个文件中,例如myServer.js,并在grunt-exec设置中使用cmd: "start node \"path\to\myServer.js"

示例:

让我们假设我的服务器文件位于以下路径:D:\SourceCodes\WebServer\myServer.js
我服务器的ip地址和端口是192.168.1.1:8080
我的网页是index.html
然后Gruntfile.js将是:

module.exports = function (grunt) {
    grunt.initConfig({
       exec: {
           run_server:{
               cwd: "D:/SourceCodes/WebServer/",
               cmd: "start node \"D:/SourceCodes/WebServer/myServer.js\""
           },
           open_web:{                
               cmd: "start chrome http://192.168.1.1:8080/index.html"
           }
    });

    grunt.loadNpmTasks('grunt-exec');
    grunt.registerTask('default', ['exec']);
}
jtjikinw

jtjikinw2#

两件事:
1.你的'connect'任务当前在等待时阻塞,你必须告诉它让grunt进程异步运行:最后调用done()

...
    server.listen(port);
    done();
});

1.现在你的构建将在你的任务列表结束时结束,并关闭你的服务器。所以你必须添加一个任务来保持它的活力。我建议使用grunt-contrib-watch,但你可以选择任何你喜欢的,只要它是一个阻塞任务:

grunt.task.run(['startServer', 'open', 'watch]);

顺便问一下,为什么要调用grunt.task.run而不是定义自己的任务序列grunt.registerTask('default', ['startServer', 'open', 'watch]);

相关问题