2017-12-10 10 views
0

Gridfs가있는 MongoDB에 여러 이미지가 업로드되었습니다. 내가 looped하고 base64 형식으로 이러한 이미지를 배열로 전달하고 nodejs 통해 표시하려고합니다.동일한 이미지가 배열에 저장 됨 - 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 "); 
    }); 

을 달성하기 followiing 코드가 있습니다. 내가 새로 고침 할 때 표시되는 이미지도 변경됩니다.

내가 모듈을 발견 잘못

감사 Gaurav

답변

0

을 뭐하는 거지 "스트림 간 약속"모든 스트림에 대한 약속을 생성 하였다. 다음은 그것의 구현입니다

// 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"); 
        }); 
      } 

희망이 누군가에게 유용합니다.