我在 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%"
}
我的整個方法可能是錯誤的,因為我是編碼新手。請幫我解決一下這個。提前致謝。
uj5u.com熱心網友回復:
您的代碼沒有任何問題,并且運行正常。
問題在于您對 blob 存盤的理解。Azure 存盤 blob(任何型別的 blob - 塊、附加或頁面)并不真正知道您是否正在嘗試將元素添加到 JSON 陣列。對于 blob 存盤,它只是一個位元組塊。
您需要做的是將 blob 讀入字串,JSON.parse用于創建 JSON 陣列物件并將資料添加到該物件。擁有該物件后,使用該物件將其轉換回字串JSON.stringify并重新上傳(即覆寫該 blob)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406464.html
標籤:
