相同的图像存储在数组中 - nodejs

时间:2017-12-10 17:42:42

标签: node.js mongodb mongoose stream

我在MongoDB中使用Gridfs上传了多个图像。我试图循环并将这些图像以base64格式传递给数组并通过nodejs显示它。

我有以下代码来实现这个

var promise = new Promise((resolve, reject) => {
    console.log('open');
    var gfs = Grid(conn.db);
    gfs.files.find({}).toArray(function(err, files) {
        if (err) {
            throw (err);
        }

        for (var i = 0; i < files.length; i++) {
            readstream[i] = gfs.createReadStream({
                _id: files[i]._id
            });
            console.log(files[i]._id);
            readstream[i].on('data', function(chunk) {
                bufs.push(chunk);
                console.log("readstream on data");
            });
            readstream[i].on('end', function() {
                fbuf = Buffer.concat(bufs);
                base64 = Buffer(fbuf).toString('base64');
                console.log("readstream on end");
                result.push(base64);
                fbuf = null;
                base64 = null;
            });
        }
    });
    if (result != undefined) {
        console.log("resolve promise if");
        resolve(result);
    }
    else {
        console.log("reject promise if");
        resolve(result);
    }
});
promise.then(function(result) {
        console.log("resolve promise.then");

        res.render("report_missing.ejs", { result2: result });
    },
    function(result) {
        console.log("reject promise then ");
    });

运行此代码时,相同的图像重复出现。如果我刷新,显示的图像也会发生变化。

我做错了什么

此致 拉夫

1 个答案:

答案 0 :(得分:0)

我找到了一个模块&#34; stream-to-promise&#34;这为所有这些流创造了一个承诺。以下是它的实现

// create a stream promise. 
var streamToPromise = require("stream-to-promise");

// create a loop for reading all files in loop.. in future may require 
cursor implementation if number of files increase

for (var i = 0; i < files.length; i++) {
                // create a readstream for the files
                readstream[i] = gfs.createReadStream({
                    _id: files[i]._id
                });

                // pass the readstream )one element at a time to the 
    promise, .then will get
// be used to pass output to a buffer
                streamToPromise(readstream[i]).then(function(buffer) {
                        base64 = Buffer(buffer).toString('base64');
                        //result is the final array which contains the 
 buffer list to pass to ejs
                        result.push(base64)
                    },

                    //This will not be executed and can have a simple console.log
                    function() {
                        console.log("this will not be executed");
                    });
            }

希望这对某人有用。