Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i read a Json file with a Azure function-Node.js

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();    
};

Here is de error:

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 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?

like image 428
Pythonist Avatar asked Mar 03 '17 12:03

Pythonist


1 Answers

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();
    });
}

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

like image 162
mathewc Avatar answered Sep 20 '22 01:09

mathewc