我创建了一个 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
获取当前工作目录。
有一种比@mathewc更快的方法。NodeJS 允许您直接要求 json 文件,
而无需显式读取 -
var result = require(__dirname + '//test.json');
根据这个github问题,__dirname的使用现在不起作用,因此根据同一问题中提到的wiki更新来自@mathewc的代码。
用context . execution context . function directory替换__dirname
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();
});
}