【问题标题】:How can i read a Json file with a Azure function-Node.js如何使用 Azure 函数-Node.js 读取 Json 文件
【发布时间】:2017-03-03 12:04:19
【问题描述】:

我创建了一个 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'而发生的,如果是这样我应该如何输入一个有效的路径?

【问题讨论】:

    标签: json node.js azure azure-functions


    【解决方案1】:

    这是一个使用内置 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 获取当前工作目录。

    【讨论】:

      【解决方案2】:

      有一种比@mathewc 更快的方法。 NodeJS 允许您直接require json 文件,无需显式读取 -> 解析步骤,也无需异步回调。所以:

      var result = require(__dirname + '//test.json');
      

      【讨论】:

        【解决方案3】:

        根据这个 github issue__dirname 的用法现在无法正常工作,因此使用同一问题中提到的 wiki 的更新用法从 @mathewc 更新代码。 p>

        __dirname 替换为 context.executionContext.functionDirectory

        var fs = require('fs');
        
        module.exports = function (context, input) {
            var path = context.executionContext.functionDirectory + '//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();
            });
        }
        

        【讨论】:

          猜你喜欢
          • 2017-07-12
          • 2023-04-10
          • 2021-12-18
          • 2017-05-28
          • 2021-01-27
          • 1970-01-01
          • 2022-01-01
          • 2016-09-06
          • 1970-01-01
          相关资源
          最近更新 更多