Search code examples
gulpglob

Copy a file to new name in same directory using gulp


I'm trying to use gulp to copy one file to the same directory with a dfferent name - the file with a different name exists already. In Unix this is simply cp ./data/file.json.bak ./data/file.json In gulp it seems much more tricky (I'm on a Windows system).

I've tried:

gulp.task('restore-json',function(){ return gulp.src('./data/file.json.bak') .pipe(gulp.dest('./data/file.json',{overwrite:true})); });

If the file exists, I get a EEXIST error. If it doesn't, it creates file.json as a directory.

I'm assuming this problem is because gulp uses globbing and effectively it's treating src and dest as paths. Do you know the most efficient way I can do this? I suppose a workaround would be to copy the file to a tmp directory and then rename and copy using glob wildcards, but is that the right way?


Solution

  • The argument that you pass to gulp.dest() is not a file name. It is the name of the directory that you want all files in your stream to be written to. See the docs.

    If you want to rename a file, use the gulp-rename plugin:

    var rename = require('gulp-rename');
    
    gulp.task('restore-json',function(){
      return gulp.src('./data/file.json.bak')
        .pipe(rename({extname:''}))
        .pipe(gulp.dest('./data/'));
    });