在 Node.js 中列出来自 Azure Blob 存储和 Readstream 的 Blob
Posted
技术标签:
【中文标题】在 Node.js 中列出来自 Azure Blob 存储和 Readstream 的 Blob【英文标题】:List blob from Azure Blob Storage and Readstream in Node.js 【发布时间】:2020-12-03 08:04:32 【问题描述】:这是我列出 Blob 的代码。
已编辑!!!
----------------------编辑---------- --------------------------------
我在这个 TypeScript 中编辑并重写了代码:
const blobServiceClient = new BlobServiceClient(`https://$accountName.blob.core.windows.net?$sasToken`,
pipeline)
const containerClient = blobServiceClient.getContainerClient(containerName)
console.log(containerClient)
if (!containerClient.exists())
console.log("the container does not exit")
await containerClient.create()
const client = containerClient.getBlockBlobClient(this.currentFile.name)
//name of uploded blob
console.log(this.currentFile.name)
//metaata from the blob
console.log(client)
//List each blobs in the container
for await (const blob of containerClient.listBlobsFlat())
console.log('\t', blob.name);
const blockBlobClient = containerClient.getBlockBlobClient(blob.name);
const downloadBlockBlobResponse = await blockBlobClient.download(0);
console.log('\nDownloaded blob content...');
console.log('\t', await streamToString(downloadBlockBlobResponse.readableStreamBody));
//end of loop
async function streamToString(readableStream)
return new Promise((resolve, reject) =>
const chunks = [];
readableStream.on("data", (data) =>
chunks.push(data.toString());
);
readableStream.on("end", () =>
resolve(chunks.join(""));
);
readableStream.on("error", reject);
);
然后我在浏览器中收到一个错误,调用:
ERROR 错误:未捕获(承诺中):TypeError:无法读取属性 'on' of undefined TypeError: Cannot read property 'on' of undefined
【问题讨论】:
尝试使用blobServiceClient.downloadToBuffer()
处理较小的文件(32 位系统最大为 1Gb)。对于较大的文件,请尝试blobServiceClient.downloadToFile()
。参数信息参考link
仍然报错:错误运行示例:blobServiceClient.downloadFile 不是函数
我的错,请尝试 for await (const blob of blobs) console.log(`Blob $i++: $blob.name`);常量 blobClient = containerClient.getBlobClient(blob.name); var 流 = blobClient.downloadToBuffer(); // stream.pipe(res)
谢谢赫曼特。如何显示 var 流的内容? “流”是否包含 blob 内容?
【参考方案1】:
通过调用download
方法下载blob。示例代码包含一个名为 streamToString
的辅助函数,用于将 Node.js 可读流读入字符串。
将此代码添加到主函数的末尾:
const blockBlobClient = containerClient.getBlockBlobClient(blob.name);
const downloadBlockBlobResponse = await blockBlobClient.download(0);
console.log('\nDownloaded blob content...');
console.log('\t', await streamToString(downloadBlockBlobResponse.readableStreamBody));
在主函数之后添加这个辅助函数:
// A helper function used to read a Node.js readable stream into a string
async function streamToString(readableStream)
return new Promise((resolve, reject) =>
const chunks = [];
readableStream.on("data", (data) =>
chunks.push(data.toString());
);
readableStream.on("end", () =>
resolve(chunks.join(""));
);
readableStream.on("error", reject);
);
更多详情可以参考这个article。
【讨论】:
我编辑了它,然后我在 TypeScript 中收到另一个错误以上是关于在 Node.js 中列出来自 Azure Blob 存储和 Readstream 的 Blob的主要内容,如果未能解决你的问题,请参考以下文章
Azure node.js API App - 在运行时失败(可能是node.js版本问题?)