js数组流为azure blobservice createBlockBlobFromStream

时间:2017-04-27 08:57:19

标签: javascript azure stream azure-storage-blobs

我有一个数组,我想使用createBlockBlobFromStream将内容上传到azure。

示例代码:

var myStream = getSomeStream();
var myStreamLength = getSomeStreamLength();
blobService.createBlockBlobFromStream(
    containerName,
    'my-awesome-stream-blob',
    myStream,
    myStreamLength,
    function(error, result, response){
        if(error){
            console.log("Couldn't upload stream");
            console.error(error);
        } else {
            console.log('Stream uploaded successfully');
        }
    });

但是我不知道如何从数组中生成myStream和myStreamLength。

1 个答案:

答案 0 :(得分:0)

您可能希望使用createWriteStreamToBlockBlob功能,这可能更容易将流上传到Azure存储。您不再需要担心流长度。然后,您可以使用以下代码从数组生成流。

var fs = require('fs');
var azure = require('azure-storage');
var Readable = require('stream').Readable;

var accountName = "youraccountname";
var accessKey = "youraccountkey";
var host = "https://yourhost.blob.core.windows.net";
var blobSvc = azure.createBlobService(accountName, accessKey, host);

var myArray = ["Saab", "Volvo", "BMW", 788, 12.3];

var rs = Readable();

for(item of myArray) {
    rs.push(String(item));
}
rs.push(null);  // indicates end-of-file basically - the end of the stream

rs.pipe(blobSvc.createWriteStreamToBlockBlob('mycontainer', 'mystream.txt'));

See here了解有关如何正确使用流的更多信息。