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

Running a command with gulp to start Node.js server

本文关键字:Node js 服务器 启动 gulp 运行 命令 使用      更新时间:2023-09-26

所以我正在使用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。这就是我想要完成的目标。在我的终端窗口中,它抱怨我的

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

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

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

.pipe

我以为这段代码:

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

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

编辑

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

安装节点的链接: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);
});

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

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,这对我的情况是故意的,但你可以适应你需要的任何东西。