使用gulp运行命令以启动Node.js服务器

Try*_*nJS 29 javascript node.js express gulp

所以我使用gulp-exec(https://www.npmjs.com/package/gulp-exec),在阅读了一些文档之后,它提到如果我只想运行一个命令,我不应该使用插件利用我在下面尝试过的代码.

var    exec = require('child_process').exec;

gulp.task('server', function (cb) {
  exec('start server', function (err, stdout, stderr) {
    .pipe(stdin(['node lib/app.js', 'mongod --dbpath ./data']))
    console.log(stdout);
    console.log(stderr);
    cb(err);
  });
})
Run Code Online (Sandbox Code Playgroud)

我正试图让我们开始我的Node.js服务器和MongoDB.这就是我想要完成的.在我的终端窗口,它抱怨我的

.pipe
Run Code Online (Sandbox Code Playgroud)

但是,我是新手,我认为这是你通过命令/任务的方式.感谢任何帮助,谢谢.

Try*_*nJS 40

gulp.task('server', function (cb) {
  exec('node lib/app.js', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    cb(err);
  });
  exec('mongod --dbpath ./data', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    cb(err);
  });
})
Run Code Online (Sandbox Code Playgroud)

供将来参考,如果有其他人遇到此问题.

上面的代码解决了我的问题.所以基本上,我发现上面是它自己的功能,因此,不需要:

.pipe
Run Code Online (Sandbox Code Playgroud)

我以为这段代码:

exec('start server', function (err, stdout, stderr) {
Run Code Online (Sandbox Code Playgroud)

是我正在运行的任务的名称,但它实际上是我将运行的命令.因此,我将其更改为指向运行我的服务器的app.js,并指向我的MongoDB.

编辑

正如下面提到的@ N1mr0d没有服务器输出,运行服务器的更好方法是使用nodemon.您可以nodemon server.js像运行一样简单地运行node server.js.

下面的代码片段是我在gulp任务中使用的,现在使用nodemon运行我的服务器:

// start our server and listen for changes
gulp.task('server', function() {
    // configure nodemon
    nodemon({
        // the script to run the app
        script: 'server.js',
        // this listens to changes in any of these files/routes and restarts the application
        watch: ["server.js", "app.js", "routes/", 'public/*', 'public/*/**'],
        ext: 'js'
        // Below i'm using es6 arrow functions but you can remove the arrow and have it a normal .on('restart', function() { // then place your stuff in here }
    }).on('restart', () => {
    gulp.src('server.js')
      // I've added notify, which displays a message on restart. Was more for me to test so you can remove this
      .pipe(notify('Running the start tasks and stuff'));
  });
});
Run Code Online (Sandbox Code Playgroud)

链接安装Nodemon:https://www.npmjs.com/package/gulp-nodemon

  • 你怎么停止其中一个服务器? (2认同)
  • 我发现https://www.npmjs.com/package/gulp-nodemon是一个非常好的解决方案,还有将nodemon集成到其中的额外好处. (2认同)

tin*_*ine 9

此解决方案显示stdout/stderr,并且不使用第三方库:

var spawn = require('child_process').spawn;

gulp.task('serve', function() {
  spawn('node', ['lib/app.js'], { stdio: 'inherit' });
});
Run Code Online (Sandbox Code Playgroud)


小智 5

您还可以像这样创建 gulp 节点服务器任务运行程序:

gulp.task('server', (cb) => {
    exec('node server.js', err => err);
});
Run Code Online (Sandbox Code Playgroud)