繁体   English   中英

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

[英]Running a command with gulp to start Node.js server

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

我试图让 gulp 启动我的 Node.js 服务器和 MongoDB。这就是我想要完成的。 在我的终端 window 中,它抱怨我的

.pipe

但是,我是 gulp 的新手,我认为这就是您传递命令/任务的方式。 感谢您的帮助,谢谢。

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

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

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

.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

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

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

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

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

gulp.task('server', (cb) => {
    exec('node server.js', err => err);
});

如果您希望您的控制台将子进程输出的所有内容都发送到 output,并将您已经设置的所有环境变量传递给子进程:

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

function runCommand(command, cb) {
  const child = exec(command, { env: process.env }, function (err) {
    cb(err);
  })
  child.stdout.on('data', (data) => {
    process.stdout.write(data);
  });
  child.stderr.on('data', (data) => {
    process.stdout.write(`Error: [${data}]`);
  });
}

请注意,out 和 err 都写入 stdout,这对我来说是有意为之,但您可以根据需要进行调整。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM