用gulp运行一个命令来启动Node.js服务器

所以我使用的是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); }); }) 

我试图让我的Node.js服务器和MongoDB启动。 这就是我想要完成的。 在我的terminal窗口,它抱怨我的

 .pipe 

不过,我是新来的吞咽,我认为这是你如何通过命令/任务。 任何帮助表示赞赏,谢谢。

 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); }); }) 

以备将来参考,如果有其他人遇到这个问题。

上面的代码解决了我的问题。 所以基本上我发现以上是自己的function,所以不需要:

 .pipe 

我认为这个代码:

 exec('start server', function (err, stdout, stderr) { 

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

编辑

正如下面提到的@ N1mr0d没有服务器输出,更好的方法来运行你的服务器将是使用nodemon。 您可以像运行nodemon server.js一样简单地运行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')); }); }); 

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

这个解决scheme显示stdout / stderr,因为它们发生并且不使用第三方库:

 var spawn = require('child_process').spawn; gulp.task('serve', function() { spawn('node', ['lib/app.js'], { stdio: 'inherit' }); });