Lionel Dcosta
Lionel Dcosta

Reputation: 176

Gulp generating images continiously

I am using the below code to generate images of different sizes when the upload happens but the below script is generating images everytime irrespective of files uploaded or not to the upload folder, Am i doing anything wrong in the below code?

const gulp = require('gulp'),
  imageresize = require('gulp-image-resize'),
  imagemin = require('gulp-imagemin'),
  pngquant = require('imagemin-pngquant'),
  path = require('path'),
  rename = require('gulp-rename'),
  paths = {
    src: 'uploads/*/*.*'
}

// create an array of image groups (see comments above)
// specifying the folder name, the ouput dimensions and
// whether or not to crop the images
const images = [
    { folder: '100x100', width: 100, height: 100, crop: true },
    { folder: '800x330', width: 800, height: 500, crop: true }
];


// images gulp task
gulp.task('images', function () {

    // loop through image groups
    images.forEach(function(type){

        // build the resize object
        var resize_settings = {
            width: type.width,
            crop: type.crop,
            // never increase image dimensions
            upscale : false
        }
        // only specify the height if it exists
        if (type.hasOwnProperty("height")) {
            resize_settings.height = type.height
        }

        gulp

        // grab all images from the folder
        .src(paths.src)

        // resize them according to the width/height settings
        .pipe(imageresize(resize_settings))

        // optimize the images
        .pipe(imagemin({
            progressive: true,
            // set this if you are using svg images
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        //rename the destination file
        .pipe(rename(function(file) {
          file.dirname = file.dirname+"/"+type.folder;
        }))

        // output each image to the dest path
        // maintaining the folder structure
        //paths.dest+type.folder
        .pipe(gulp.dest(function(file){
          return path.join(path.dirname(file.path), "../", "../");
        }));
    });
});

gulp.task('watch', function(){
     gulp.watch('uploads/**', ['images']);
})

gulp.task('default', ['watch']);

Upvotes: 0

Views: 114

Answers (2)

Lionel Dcosta
Lionel Dcosta

Reputation: 176

I have updated my code to use "gulp-once" which works better compare to other libs.

Upvotes: 0

eavidan
eavidan

Reputation: 5564

It is because of the way gulp watch works. You can consult the following: use gulp-chached

Upvotes: 1

Related Questions