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



>我正在尝试使用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));
});

有什么想法吗?

以防万一其他人在看这个,这就是我降落的地方......

return new Promise(async (resolve, reject) => {
let bucket = new mongodb.GridFSBucket(db, {
bucketName: 'Binaries'
});
let objectID = new mongodb.ObjectID(fileInformation._id);
// temporary variable to hold image
var data = [];
// create the download stream
let downloadStream = bucket.openDownloadStream(objectID);
downloadStream.on('data', (chunk) => {
data.push(chunk);
});
downloadStream.on('error', async (error) => {
reject(error);
});
downloadStream.on('end', async () => {
// convert from base64 and write to file system
let bufferBase64 = Buffer.concat(data)
let bufferDecoded = Buffer.from(bufferBase64.toString(), 'base64');
fs.writeFileSync(fileName, bufferDecoded, 'binary');
resolve(fileName);
});
});

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

前任。

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

更多关于 Buffer.from(( 函数的信息在这里。

最新更新