1

I have a server and it gets a lot of image uploads. The app uploading the images is based in PHP. However, I want to use Node to watch the upload folder, then run imagemin on any new images.

I was thinking I would use npm packages 'watch' and 'imagemin'. I am not sure how to configure them exactly though or how to have it run all the time.

So far I have the following which I can turn on manually:

var Imagemin = require('imagemin');
var watch = require('watch');
var imagemin = new Imagemin()
  .use(Imagemin.pngquant());
watch.createMonitor('images', function (monitor) {
  monitor.files['images/*.png']
  monitor.on("created", function (file) {
    compressImage(file);
  })
  monitor.on("changed", function (file) {
    compressImage(file);
  });
});

function compressImage(file) {
  var dest, path;
  path = f.split('/');
  path.pop();
  dest = path.join('/');
  imagemin.src(file).dest(dest).run();
}

After a couple of files are added though I get a warning about a possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit and then it stops working.

Is there a better way to do this and how can I run it automatically?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Sean
  • 1,758
  • 3
  • 20
  • 34

1 Answers1

2

To deal with the recursive firing of the watch function on change, one possible solution is this: Whenever your compression function runs, have it store the filename in a var. On your change listener function, just add

If (file !== lastFile) {
   //do something
}

There is another module that is quite similar you could try, called chokidar.

Has very similar hooks as watch:

watcher.on('add', function(path) { log('File', path, 'has been added'); })
watcher.on('change', function(path) { log('File', path, 'has been changed'); })

Examples here: Watch Files and Directories

tpie
  • 6,021
  • 3
  • 22
  • 41
  • 1
    I think the issue is that when it overwrites the image, it sees that it changed and tries to compress it again. I am not sure how I can accomplish this without moving the file to another location. – Sean Apr 29 '15 at 20:01
  • 1
    You could also potentially add a second layer of validation that checks last filename and a time stamp. That way if the same file gets uploaded again it will get compressed again, as long as it wasn't in the last 10 seconds or whatever. – tpie Apr 29 '15 at 20:10
  • 1
    I modified the uploads to old files are deleted instead of overwritten which means I just need the on add event. I believe I have the script working now, just need to get it to run when the server starts. – Sean Apr 30 '15 at 11:02