通过节点从GridFS读取时如何解码base64文件?

问题描述 投票:0回答:1

我正在尝试使用Node从MongoDB GridFS集合中读取以base64编码的文件。我已经能够将文件从MongoDB保存到我的本地计算机上,但是它是base64格式,我想将其保存为未编码。

理想情况下,我想“即时”解码文件而不必保存一次,然后读取>解码>将其写回到文件系统。

我的代码当前看起来像这样...

return new Promise(async (resolve, reject) => {
    let bucket = new mongodb.GridFSBucket(db, {bucketName: 'Binaries'});
    let objectID = new mongodb.ObjectID(fileID);

    // create the download stream
    bucket.openDownloadStream(objectID)
        .once('error', async (error) => {
            reject(error);
        })
        .once('end', async () => {
            resolve(downloadPath);
        })
        // pipe the file to the stream
        .pipe(fs.createWriteStream(downloadPath));
});

有什么想法吗?

node.js mongodb base64 gridfs
1个回答
0
投票

Node具有内置的缓冲区解析器Buffer.from(string[, encoding]),您可以将base64编码的字符串传递给它,并从另一侧获取字节流,然后可以轻松地将其转换为.toString()

例如

let whatYouNeed = Buffer.from(gridFsData, 'base64').toString();

有关Buffer.from()函数here的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.