如何使用 @azure/storage-blob sdk 附加 blob 文件? (节点)

How do I append a blob file using @azure/storage-blob sdk ? (NodeJS)

我在 blob 存储中的文件“mainfile.json”具有以下内容:

[
  { "name": "abc", "id": "01", "location": "random" },
  { "month": "Jan", "project": "50%", "training": "50%" },
]

我要添加的数据是这样的:

{"month": "Feb", "project":"60%", "training":"40%"}

我希望它是这样的:

[
  { "name": "abc", "id": "01", "location": "random" },
  { "month": "Jan", "project": "50%", "training": "50%" },
  {"month": "Feb", "project":"60%", "training":"40%"}
]

我正在使用@azure/storage-blob sdk 来执行相同的操作,下面是我的代码:

const blobServiceClient = require("./getCred");
const fs = require("fs");

async function appendBlob() {
  const containerClient =
    blobServiceClient.getContainerClient("containername");
  //gets the main content from a blob
  const blobClient = containerClient.getBlobClient("mainfile.json");
  //the new appended content gets written into this blob
  const blockBlobClient = containerClient.getBlockBlobClient("data.json");
  // the data that needs to be appended
  const data = fs.readFileSync("new-data.json", "utf-8", (err) => {
    if (err) {
      console.log("File not read");
    }
  });

  // Get blob content from position 0 to the end
  // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
  const downloadBlockBlobResponse = await blobClient.download();
  const downloaded = (
    await streamToBuffer(downloadBlockBlobResponse.readableStreamBody)
  ).toString();
  const append = await appendingFile(downloaded, data);

  const uploadBlobResponse = await blockBlobClient.upload(
    append,
    append.length
  );
  console.log(
    `Uploaded block blob to testing.json successfully`,
    uploadBlobResponse.requestId
  );

  // [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
  async function streamToBuffer(readableStream) {
    return new Promise((resolve, reject) => {
      const chunks = [];
      readableStream.on("data", (data) => {
        chunks.push(data instanceof Buffer ? data : Buffer.from(data));
      });
      readableStream.on("end", () => {
        resolve(Buffer.concat(chunks));
      });
      readableStream.on("error", reject);
    });
  }

  async function appendingFile(content, toBeAdded) {
    return new Promise((resolve, reject) => {
      let temp = content.concat(toBeAdded);
      console.log(temp);
      resolve(temp);
      reject(new Error("Error occurred"));
    });
  }
}

但我得到以下输出:

[
  {
    "name": "KK",
    "id": "01",
    "location": "chennai"
  },
  {
    "month": "December",
    "project": "50%",
    "training": "50%"
  }
]
{
  "month": "January",
  "adaptive-cards": "50%",
  "azure-func-app": "50%"
}

我的整个方法可能是错误的,因为我是编码新手。请帮我解决一下这个。提前致谢。

您的代码没有任何问题,并且工作正常。

问题在于您对 blob 存储的理解。 Azure 存储 blob(任何类型的 blob - 块、追加或页面)并不真正知道您是否正在尝试将元素添加到 JSON 数组。对于 blob 存储,它只是一个字节块。

您需要做的是将 blob 读入字符串,使用 JSON.parse 创建一个 JSON 数组对象并将数据添加到该对象。获得该对象后,使用 JSON.stringify 将其转换回字符串并重新上传该字符串(即覆盖 blob)。