我创建了一个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/