Azure函数 – NodeJS – 作为stream的响应主体

当你点击给定的Azure函数端点时,我想从Blob存储中返回一个文件。 这个文件是二进制数据。

根据Azure存储Blob文档,最相关的调用似乎是以下内容,因为它是唯一不需要将文件写入临时文件的getBlobToStreamgetBlobToStream

然而,这个调用获取Blob并将其写入stream中。

有没有一种方法使用Azure函数将Stream作为res.body的值,以便我可以从存储中获取Blob内容并立即将其写入响应?

要添加一些代码,试图得到这样的工作:

 'use strict'; const azure = require('azure-storage'), stream = require('stream'); const BLOB_CONTAINER = 'DeContainer'; module.exports = function(context){ var file = context.bindingData.file; var blobService = azure.createBlobService(); var outputStream = new stream.Writable(); blobService.getBlobToStream(BLOB_CONTAINER, file, outputStream, function(error, serverBlob) { if(error) { FileNotFound(context); } else { context.res = { status: 200, headers: { }, isRaw: true, body : outputStream }; context.done(); } }); } function FileNotFound(context){ context.res = { status: 404, headers: { "Content-Type" : "application/json" }, body : { "Message" : "No esta aqui!."} }; context.done(); } 

不幸的是,我们还没有在NodeJS中实现stream式支持 – 这是在积压: https : //github.com/Azure/azure-webjobs-sdk-script/issues/1361

如果你不是绑定到NodeJ打开使用C#函数,而是直接在input绑定和stream请求输出中使用存储sdk对象,而不是使用中间对象方法。

虽然@Matt Manson的回答绝对是基于我问我问题的方式,但下面的代码片段可能对于在这个问题上磕磕绊绊的人更有用。

尽pipe我无法直接将Stream发送到响应主体,但我可以使用一个自定义stream将数据捕获到Uint8Array中,然后将其发送到响应主体。

注意:如果文件非常大,则会占用大量内存。

 'use strict'; const azure = require('azure-storage'), stream = require('stream'); const BLOB_CONTAINER = 'deContainer'; module.exports = function(context){ var file = context.bindingData.file; var blobService = azure.createBlobService(); var outputStream = new stream.Writable(); outputStream.contents = new Uint8Array(0);//Initialize contents. //Override the write to store the value to our "contents" outputStream._write = function (chunk, encoding, done) { var curChunk = new Uint8Array(chunk); var tmp = new Uint8Array(this.contents.byteLength + curChunk.byteLength); tmp.set(this.contents, 0); tmp.set(curChunk, this.contents.byteLength); this.contents = tmp; done(); }; blobService.getBlobToStream(BLOB_CONTAINER, file, outputStream, function(error, serverBlob) { if(error) { FileNotFound(context); } else { context.res = { status: 200, headers: { }, isRaw: true, body : outputStream.contents }; context.done(); } });//*/ } function FileNotFound(context){ context.res = { status: 404, headers: { "Content-Type" : "application/json" }, body : { "Message" : "No esta aqui!"} }; context.done(); }