Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulp change working directory for entire task

I'm working on a gulp file that contains tasks for both the frontend and the backend of my site.
The task below for example will concat my scripts into app.js:

gulp.task 'frontend:scripts', ->
    gulp.src frontendPath(scriptsFolder, scriptsPattern)
        .pipe sourcemaps.init()
        .pipe coffee()
        .pipe concat 'app.js'
        .pipe sourcemaps.write('.')
        .pipe gulp.dest frontendPath(tempFolder, scriptsFolder)

As you can see I've created a helper to provide the correct frontend path:

frontendPath = (dirs...) -> path.join.apply null, ['frontend'].concat(dirs)

But I have to be really careful that all the steps of my task (especially .src and .dest) are executed in the frontend folder.

I know that you can use the { cwd: 'frontend' } option to change the working directory for .src and .dest. But is there a way to change the whole working directory for a task?

like image 978
Zyphrax Avatar asked Oct 11 '14 03:10

Zyphrax


2 Answers

Use process.chdir to change the working directory. We can make the change anywhere in a gulpfile, or in your situation, change it within a task.

gulp.task('frontend', function(){
  process.chdir('...');
  gulp.src(...)
});

gulp.task('backend', function(){
  process.chdir('...');
  gulp.src(...)
});

Make sure using the latest version of gulp, this feature seems to be added recently.

like image 193
gfaceless Avatar answered Oct 07 '22 19:10

gfaceless


With the way that gulp works, it doesn't make sense to "change directories" in the steps between src and dest.

gulp.src reads files from disk into memory. The .pipes thereafter just pipe the contents of those files (and metadata related to the files - see Vinyl file objects for more info) to other javascript functions, each of which just operates on the in-memory versions of the file. That means they don't know about a working directory, or care about one. They just see incoming data about files come in through pipe, do stuff to that data, and send it out through the next .pipe.

So I think that if you're truly paranoid about being in the parent director, a cwd to src and dest is the best you can do.

All of that to say, you could look at shelljs, which allows you to change directories for the current node process. I think this might be considered an anti-pattern when piping things around, but might be worth a shot.

like image 28
thataustin Avatar answered Oct 07 '22 19:10

thataustin