通过Node从GridFS读取时如何解码base64文件? [英] How do decode base64 file when reading from GridFS via Node?
本文介绍了通过Node从GridFS读取时如何解码base64文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Node从MongoDB GridFS集合中读取以base64编码的文件.我已经能够将文件从MongoDB保存到我的本地计算机上,但是它是base64格式的,我想以未编码的方式保存它.
I'm trying to read a file encoded in base64 from a MongoDB GridFS collection using Node. I have been able to get the file saved from MongoDB to my local machine, but it's in base64 format and I want to save it unencoded.
理想情况下,我想即时"解码文件而不必保存一次,然后读取>解码>将其写回到文件系统中.
Ideally I would like to decode the file "on-the-fly" without having to save once, to then read > decode > write it back to the filesystem.
我的代码当前看起来像这样...
My code currently looks like this...
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));
});
有什么想法吗?
推荐答案
以防万一其他人在看这个东西,这就是我降落的地方...
Just in case anyone else is looking at this, here's where I landed...
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从GridFS读取时如何解码base64文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文