Unable to read readableStreamBody from downloaded

2019-07-31 16:28发布

问题:

I can I check the internal buffer to see if my text data is present? Am I using node.js' Stream.read() correctly?

I have a text file as a blob stored on azure-storage. When I download the blob I get readable stream as well as info about the blob. The return data has a contentLength of 11 which is correct.

I am unable to read the steam. It always returns null. The node.js docs say,

The readable.read() method pulls some data out of the internal buffer and returns it. If no data available to be read, null is returned.

According to Node.js there is no data available.

async function downloadData(){
    const textfile = "name.txt"

    const containerURL = ContainerURL.fromServiceURL(serviceURL, "batches")
    const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, textfile );
    let baseLineImage = await blockBlobURL.download(aborter, 0)

    console.log(baseLineImage.readableStreamBody.read())
    return

}

The method blobBlobURL.download downloads the data. More specific to Azure it,

Reads or downloads a blob from the system, including its metadata and properties. You can also call Get Blob to read a snapshot.

In Node.js, data returns in a Readable stream readableStreamBody In browsers, data returns in a promise blobBody

回答1:

According to your code, I see you were using Azure Storage SDK V10 for JavaScript.

In the npm page of this package @azure/storage-blob, there is an async function named streamToString in the sample code which can help you to read the content from readable stream, as below.

// A helper method used to read a Node.js readable stream into 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);
  });
}

Then, your code will be writen like below.

async function downloadData(){
    const textfile = "name.txt"

    const containerURL = ContainerURL.fromServiceURL(serviceURL, "batches");
    const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, textfile );
    let baseLineImage = await blockBlobURL.download(aborter, 0);

    let content = await streamToString(baseLineImage.readableStreamBody);
    console.log(content)
    return content
}

Hope it helps.