json - 如何使用 Azure 函数 Node.js 读取 Json 文件

标签 json node.js azure azure-functions

我创建了一个Azure时间触发器函数,我想和他一起读取一个Json文件。我确实安装了 read-json 和 jsonfile 软件包并尝试了两者,但它不起作用。这是一个示例函数

module.exports = function (context, myTimer) {
   var timeStamp = new Date().toISOString();
   var readJSON = require("read-json");

    readJSON('./publishDate.json', function(error, manifest){
        context.log(manifest.published);
    });
    context.log('Node.js timer trigger function ran!', timeStamp);
    context.done();    
};

这是错误:

TypeError: Cannot read property 'published' of undefined
    at D:\home\site\wwwroot\TimerTriggerJS1\index.js:8:29
    at ReadFileContext.callback (D:\home\node_modules\read-json\index.js:14:22)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13).

Json 文件与 index.js 位于同一文件夹中。我假设这个错误是由于路径“./publishDate.json”而发生的,如果是这样,我应该如何输入有效的路径?

最佳答案

这是一个使用内置 fs 模块的工作示例:

var fs = require('fs');

module.exports = function (context, input) {
    var path = __dirname + '//test.json';
    fs.readFile(path, 'utf8', function (err, data) {
        if (err) {
            context.log.error(err);
            context.done(err);
        }

        var result = JSON.parse(data);
        context.log(result.name);
        context.done();
    });
}

注意使用__dirname来获取当前工作目录。

关于json - 如何使用 Azure 函数 Node.js 读取 Json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42578431/

相关文章:

jquery 验证显示多个错误

php - 处理 PHP JSON 对象中的数据

javascript - Node.js https.request : Access the requested data from the callback response scope

node.js - 有什么方法可以在应用崩溃时自动重启?

python - mktime 参数超出范围

azure - 如何在azure文档数据库中向另一个查询提供一个查询的结果

json - Amber 和本地存储,asJSON?

javascript 未加载到 HTML 文件中 - nodejs + http

c# - Visual Studio 中有没有办法从空 ASP.NET Web 应用程序开始配置 Web 部署的默认起始页?

javascript - 如何检查并返回数据直到没有匹配项?