NodeJS - streams with empty data. How to deal with?

I have some code like so:

var readImage = function(snapshot) {
  var s = new cv.ImageDataStream()
  var p = new Promise(function(resolve, reject) {
    s.on("load", function(matrix) {
      resolve(matrix);
    });
  })
  snapshot.pipe(s);
  return p;
};    

Where cv is node-opencv. Unfortunately, it calls out to some C++, which fails if the data it receives is empty or invalid. It just explodes (no exception handling). Is there a way I can resolve that snapshot stream to a buffer or something, check it's contents, and then convert it back into a stream and pipe it back into cv?

I believe that if you are listening for errors on a stream it won't raise an exception and call your callback instead.

Try to...

s.on('error', function(e) {
    // handle e
})

...to prevent an exception to be thrown.