pipe file without downloading it in azure function

Viewed 332

I would like to pass a readstream file to an API without downloading it in local then create a readStream using fs module.

Here's my code example

const blobServiceClient = BlobServiceClient.fromConnectionString(
    process.env.CONNEXION_STRING
  );
  const containerClient = blobServiceClient.getContainerClient(
    params.containerName
  );
  const blobClient = containerClient.getBlobClient(process.env.PBIX_LOCATION);
  let blobData;
  try {
    blobData = await blobClient.downloadToFile(`${params.reportName}.pbix`);
    console.log(blobData);
  } catch (error) {
    console.log(error);
  }
  var options = {
    method: "POST",
    url: `https://api.powerbi.com/v1.0/myorg/groups/${params.groupId}/imports?datasetDisplayName=${params.reportName}`,
    headers: {
      "Content-Type": "multipart/form-data",
      Authorization: `Bearer ${params.accessToken} `,
    },
    formData: {
      "": {
        value: fs.createReadStream(`${params.reportName}.pbix`),
        options: {
          filename: `${params.reportName}.pbix`,
          contentType: null,
        },
      },
    },
  };
  //check if file keep in mem
  return new Promise(function (resolve, reject) {
    request(options, function (error, response) {
      if (error) reject(error);
      resolve(response.body);
      fs.unlinkSync(`${params.reportName}.pbix`);
    });
  });
};

Actually this code is working on local, but not when deployed to azure function ( may be because of file download ) .

I would like to achieve this without using downloadToFile function

1 Answers

Use readableStreamBody, see the official sample:

 // List blobs
  i = 1;
  for await (const blob of containerClient.listBlobsFlat()) {
    console.log(`Blob ${i++}: ${blob.name}`);
  }

  // Get blob content from position 0 to the end
  // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
  // In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
  const downloadBlockBlobResponse = await blockBlobClient.download(0);
  console.log(
    "Downloaded blob content",
    (await streamToBuffer(downloadBlockBlobResponse.readableStreamBody)).toString()
  );

Refer to: Azure Storage samples using v12 JavaScript client libraries

Related