Excute command in gulp for sub folder

2019-08-15 19:41发布

My project is structured as follows:

myapp
 -server.js
 -test
 --testcontent
 ---package.json
 -package.json

I have two package.json files and I want to run npm install on the package.json inside the testcontent folder.

If in the command line I go to myapp/test/testcontent and run npm install it works and it creates a new folder node_modules with the dependencies from the correct package.json. How can that be done from within gulp?

I tried the following but it uses the package.json in myapp not the one in the testcontent sub folder:

gulp.task('default', function () {
    var options = {
        continueOnError: true, // default = false, true means don't emit error event
        pipeStdout: true, // default = false, true means stdout is written to file.contents
        customTemplatingThing: "test" // content passed to gutil.template()
    };
    var reportOptions = {
        err: true, // default = true, false means don't write err
        stderr: true, // default = true, false means don't write stderr
        stdout: true // default = true, false means don't write stdout
    }
    gulp.src('test/testcontent/')
        .pipe(exec('npm install' , options))
        .pipe(exec.reporter(reportOptions));
});

1条回答
beautiful°
2楼-- · 2019-08-15 19:45

gulp-exec is the wrong tool for this job. In fact the authors of the gulp-exec plugin explicitly advise against using it the way you are doing:

Note: If you just want to run a command, just run the command, don't use this plugin

Instead you use the node.js built-in child_process.spawn(). You can pass the directory where the command should be executed using the cwd option:

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

gulp.task('default', function(done) {
  spawn('npm', ['install'], { cwd: 'test/testcontent/', stdio: 'inherit' })
    .on('close', done);
});
查看更多
登录 后发表回答