【问题标题】:How to read json file from storage blob container with azure function using javascript?如何使用 javascript 从具有 azure 功能的存储 blob 容器中读取 json 文件?
【发布时间】:2019-12-25 13:22:39
【问题描述】:

我是 azure 的新手,我想创建 azure 函数,它将从 azure 存储容器 file.json 中读取内容。

文件夹结构: 存储帐户名称: storageaccounttest 容器名称:测试 文件名:file.json

文件.json:

[

    {
        "name":"Kate",
        "age":"28"
    },
    {
        "name":"John",
        "age":"30"
    }
]

存储帐户上的 Cors:启用。

Environemnts 变量添加:process.env.AZURE_STORAGE_NAME 和 process.env.AZURE_STORAGE_KEY 和 process.env.AZURE_CONNECTION_STRING

我正在使用 VisualStudioCode 来部署该功能。 我在本地安装了依赖项: “依赖”:{ “天蓝色存储”:“^2.10.3”, “dotenv”:“^8.1.0” }

我选择 javascript -> HttpTrigger fn-> 匿名选项

我正在使用 getBlobToText fn。 我的 index.js:

var storage = require('azure-storage');
var blobService = storage.createBlobService();
var containerName = 'test';
var blobName = 'file.json';

module.exports =  blobService.getBlobToText(
    containerName,
    blobName,
    function(err, blobContent) {
        if (err) {
            console.error("Couldn't download blob");
            console.error(err);
        } else {
            console.log("Sucessfully downloaded blob");
            console.log(blobContent);
        }
    });

Fn 部署成功,但我看不到结果。 启动后,fn 以状态 500 结束,内部服务器错误,控制台:过去 1 分钟内没有新的跟踪。

我做错了什么?

【问题讨论】:

  • 它在本地工作吗?如果是,请确保您已在 Portal 应用设置刀片中添加了相关的存储应用设置。
  • 是的,它在本地工作正常。您指的是哪些设置?
  • 好的,我用 context.bindings 做到了

标签: javascript azure-functions


【解决方案1】:

只是为了帮助遇到同样问题的其他人而总结的。

我认为您使用context.binding.responseblobContent 值传递给输出响应,正如官方文档Azure Functions JavaScript developer guide 所说。

这是我的示例代码,带有Promise 功能来解决它​​。

var azure = require('azure-storage');
var blobService = azure.createBlobService();
var containerName = 'test';
var blobName = 'file.json';

async function getBlobContent(containerName, blobName) {
  return new Promise((resolve, reject) => {
    blobService.getBlobToText(containerName, blobName, function(err, blobContent) {
        if (err) {
            reject(err);
        } else {
            resolve(blobContent);
        }
    });
  });
}

module.exports = async function (context, req) {
    await getBlobContent(containerName, blobName).then(
        function(content) {
            context.res = {
                headers: {"Content-Type": "application/json"},
                body: content
            }
        }, function(error) {
            context.res = {
                status: 400,
                body: error
            }
        }
    );
};

如下图所示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-26
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多