Search code examples
node.jsstreamimdb

nodejs trying to read stream of jpg data from return function


Im trying to get poster data back from omdb API, found at github.

I am getting all other movie information, but I am struggling with streams, the way I think you should get the poster from this function.

The code in the omdb API looks like this:

// Get a Readable Stream with the jpg image data of the poster to the movie,
// identified by title, title & year or IMDB ID.
module.exports.poster = function (options) {
    var out = new stream.PassThrough();

    module.exports.get(options, false, function (err, res) {
        if (err) {
            out.emit('error', err);
        } else if (!res) {
            out.emit('error', new Error('Movie not found'));
        } else {
            var req = request(res.poster);
            req.on('error', function (err) {
                out.emit('error', err);
            });
            req.pipe(out);
        }
    });

    return out;
};

How could I get the poster from this? I call it using omdb.poster(options), however im not sure what the options should be either.

If anyone could help me or point me in the right direction, I would be grateful!


Solution

  • You need to read and then write the stream to something. Sample below would write a JPEG file out to your filesystem containing the poster.

    const omdb = require('omdb');
    const fs = require('fs');
    const writeStream = fs.createWriteStream('test.jpg')
    
    omdb.poster({ title: 'Saw', year: 2004 })
        .on('data', (data) => {
            writeStream.write(data)
        })
        .on('end', () => {
            writeStream.end();
        });