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

lztngnrs  于 2023-01-10  发布在  Gulp
关注(0)|答案(4)|浏览(211)

因此,我使用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

然而,我是个新手,我想这就是你传递命令/任务的方式。任何帮助都是感激的,谢谢。

cgyqldqp

cgyqldqp1#

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

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

pgvzfuti

pgvzfuti2#

此解决方案在stdout/stderr出现时显示它们,并且不使用第三方库:

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

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

kknvjkwl3#

您还可以创建gulp节点服务器任务运行器,如下所示:

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

jum4pzuy4#

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

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,这是我的情况下故意的,但您可以根据需要进行调整。

相关问题