2017-03-03 19 views
2

我已經創建了Azure時間觸發器函數,並且想要與他一起閱讀Json文件。我確實安裝了read-json和jsonfile軟件包,並嘗試使用這兩種軟件包,但它沒有奏效。下面是一個例子功能我如何讀Azure函數的Json文件-node.js

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'路徑發生的,如果是的話我應該如何輸入一個有效的路徑?

回答

4

下面是一個使用內置的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獲取當前的工作目錄。

+0

Thanx @mathewc它的工作完美。 –

1

有比@ mathewc更快的方法。 NodeJS允許您直接使用require json文件,而不需要顯式的讀 - >解析步驟,也不需要異步回調。所以:

var result = require(__dirname + '//test.json');