Search code examples
javascriptnode.jsexpressstreamgraphicsmagick

Order of execution in Node js streams


I want to validate an image before I am saving it to disk. I am using the GM library.

// Running an Express app

app.post('/image', function(req, res) {
  var stream = 
    gm(req)
     .size({ bufferStream: true }, function(err, size) {    
       if (size.width > 2000) {
        return res.send('Too big, aborting upload!');
       }
     })
     .stream(function(err, stdout, stderr) { 
      save(stdout, res);    
    });    
});

function save(stream, res) {
  var file = fs.createWriteStream('./test-image.png');
  stream.pipe(file);
  res.send('Saving image to disk');
}

My problem is that I execute the save function before I have validated the image. How can I make sure that the stream only continues if it is valid?


Solution

  • GM adds all the operations to a list and executes them before the write operation so this behavior makes sense. Here's a workaround:

    app.post('/image', function(req, res) {                                 
      var file = fs.createWriteStream('./test-image.png');
    
      var stream = 
        gm(req)
         .size({ bufferStream: true }, function(err, size) {    
           if (size.width > 2000) {
            return res.send('Too big, aborting upload!');
           }
           this.stream().pipe(file);  
           res.send('Saving image to disk');
    
    });