dewwwald
dewwwald

Reputation: 297

Gulp write file if none exist

How can I make gulp write a file only if there is no existing file.

The bellow solution works for gulp 4.0 which is in alpha.

// for when gulp 4.0 releases
.pipe(gulp.dest(conf.plugScss.dist, {overwrite: false}))

Upvotes: 0

Views: 1363

Answers (2)

dewwwald
dewwwald

Reputation: 297

I solved it by going with gulp-tap.

conf.plugScss.files.forEach(function (file, index, files)
    {
        gulp.src(file)
            .pipe(rename({
                prefix: "_",
                extname: ".scss"
            }))
            .pipe(tap(function (file, t)
            {
                file.contents = Buffer.concat([
                    new Buffer('HEADER'),
                    file.contents
                ]);
                var fileCheck = function(err, stat) {
                    if (err !== null && err.code == 'ENOENT')
                    {
                        fs.writeFile('dist/' + file.path.split('/').reverse()[0], file.contents)
                    }
                    return null;
                }
                fs.stat('dist/' + file.path.split('/').reverse()[0], fileCheck.bind(this));
            }));
            // for when gulp 4.0 releases
            // .pipe(gulp.dest(conf.plugScss.dist, {overwrite: false}))
    });

Upvotes: 0

Sven Schoenung
Sven Schoenung

Reputation: 30574

There is no exact equivalent in gulp 3.x, but you can use gulp-changed to achieve the same thing.

gulp-changed is usually used to write only those files that have changed since the last time they were written to the destination folder. However you can provide a custom hasChanged function. In your case you can write a function does nothing but check if the file already exists using fs.stat():

var gulp = require('gulp');
var changed = require('gulp-changed');
var fs = require('fs');

function compareExistence(stream, cb, sourceFile, targetPath) {
  fs.stat(targetPath, function(err, stats) {
    if (err) {
       stream.push(sourceFile);
    }
    cb();
  });
}

gulp.task('default', function() {
  return gulp.src(/*...*/)
    .pipe(changed(conf.plugScss.dist, {hasChanged: compareExistence}))
    .pipe(gulp.dest(conf.plugScss.dist));
});

Upvotes: 4

Related Questions