等待readStream结束并返回数据

Ale*_*ide 2 javascript asynchronous stream node.js

这是我的代码:

downloadFile(file_id) {
    var mongoose = require('mongoose');
    var Grid = require('gridfs-stream');
    var fs = require('fs');

    mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
    var conn = mongoose.connection;
    Grid.mongo = mongoose.mongo;
    var gfs = Grid(conn.db);
    console.log('downloadfile', file_id);
    var read_stream = gfs.createReadStream({_id: file_id});
    let file = [];
    read_stream.on('data', function (chunk) {
        file.push(chunk);
    });
    read_stream.on('error', e => {
        console.log(e);
    });
    return read_stream.on('end', function () {
        console.log('file', file); // This logs the file buffer
        return file;
    });
}
Run Code Online (Sandbox Code Playgroud)

这就是我尝试使用它的方式:

Account.findById(req.params._id)
    .then(async account => {
        const file = await functions.downloadFile(account.employer.logo);
        console.log(file); // This logs the readStream data
        res.render('users/employer/booth', {
            title: 'Employer Booth',
            user: req.user,
            postings: postings,
            employer: account.employer,
            event: event,
            logo: logo,
        });
    });
Run Code Online (Sandbox Code Playgroud)

我想在回调中获取下载的文件很容易,但是我怎样才能将这个文件传递回去,并使代码执行等待呢?

这就是记录的文件的样子file [ <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 fa 00 00 00 fa 08 06 00 00 00 88 ec 5a 3d 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 20 00 ... > ]

所以总结一下。现在,代码不会等待。它记录 readStream 本身,然后记录文件数据。如何让它等待流结束并将文件返回到我的路由器?

fro*_*dev 6

将您的函数包装downloadFile到 Promise 对象中,并仅在完全读取文件后才能解析,并且在rejectPromise 出现错误的情况下。

更新代码

function downloadFile(file_id) {
    return new Promise((resolve, reject) => {
        var mongoose = require('mongoose');
        var Grid = require('gridfs-stream');
        var fs = require('fs');

        mongoose.connect(config.db, { useNewUrlParser: true },).catch(e => console.log(e));
        var conn = mongoose.connection;
        Grid.mongo = mongoose.mongo;
        var gfs = Grid(conn.db);
        console.log('downloadfile', file_id);
        var read_stream = gfs.createReadStream({ _id: file_id });
        let file = [];
        read_stream.on('data', function (chunk) {
            file.push(chunk);
        });
        read_stream.on('error', e => {
            reject(e);
        });
        return read_stream.on('end', function () {
            console.log('file', file); // This logs the file buffer
            resolve(file);
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,它是承诺的成功处理程序。 (2认同)