我如何使用 Azure 函数-Node.js 读取 Json 文件 [英] How can i read a Json file with a Azure function-Node.js

查看:19
本文介绍了我如何使用 Azure 函数-Node.js 读取 Json 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created an Azure time trigger function and i want to read a Json file with him. I did install read-json and jsonfile packages and tried with both, but it did not work. Here is an example function

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:homesitewwwrootTimerTriggerJS1index.js:8:29
    at ReadFileContext.callback (D:home
ode_modules
ead-jsonindex.js:14:22)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13).

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

Json file is in same folder with the index.js. I assume that this error occurs because of the path './publishDate.json', if so how should i type a valid path?

推荐答案

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

Here's a working example that uses the built in fs module:

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 来获取当前工作目录.

Note the use of __dirname to get the current working directory.

这篇关于我如何使用 Azure 函数-Node.js 读取 Json 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆