6

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?

Janusz Nowak
  • 2,595
  • 1
  • 17
  • 36
Pythonist
  • 115
  • 2
  • 12

3 Answers3

11

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.

mathewc
  • 13,312
  • 2
  • 45
  • 53
4

There is a quicker way than @mathewc's. NodeJS allows you to require json files directly without the explicit read -> parse steps nor without an async callback. So:

var result = require(__dirname + '//test.json');
Larry Maccherone
  • 9,393
  • 3
  • 27
  • 43
2

According to this github issue the usage of __dirname wont work now, so updating the code from @mathewc with the update usage as per the wiki referred in the same issue.

replace __dirname with 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();
    });
}
Sanjeevi Subramani
  • 501
  • 1
  • 5
  • 16