2016-02-14 66 views
21

假設對於API的每個響應,我需要將響應中的值映射到我的web應用程序中現有的json文件,並顯示json的值。在這種情況下讀取json文件有什麼更好的方法? require或fs.readfile。請注意,可能會有數千個請求同時進入。閱讀json文件的內容與require與fs.readFile

請注意,我不希望在運行時文件有任何更改。

request(options, function(error, response, body) { 
    // compare response identifier value with json file in node 
    // if identifier value exist in the json file 
    // return the corresponding value in json file instead 
}); 

回答

31

我想你會JSON.parse用於比較的JSON文件,在這種情況下,require更好,因爲它會分析該文件就和它的同步:

var obj = require('./myjson'); // no need to add the .json extension 

如果你必須使用該文件數以千計的請求,要求它一旦你的請求處理程序之外,就是這樣:

var myObj = require('./myjson'); 
request(options, function(error, response, body) { 
    // myObj is accessible here and is a nice JavaScript object 
    var value = myObj.someValue; 

    // compare response identifier value with json file in node 
    // if identifier value exist in the json file 
    // return the corresponding value in json file instead 
}); 
+0

是不是'需要'同步?根據JSON文件或用例的大小,fs.readFile應該更好。 –

+0

我也同意,甚至建議,使用管道更大的文件。爲了實現大型連接,連接的鴿舍(空間/時間索引)也證明可以提高效率。 –

37

有兩個版本fs.readFile,他們是

異步版本

require('fs').readFile('path/test.json', 'utf8', function (err, data) { 
    if (err) 
     // error handling 

    var obj = JSON.parse(data); 
}); 

同步版本

var json = JSON.parse(require('fs').readFileSync('path/test.json', 'utf8')); 

要使用require解析JSON文件,如下

var json = require('path/test.json'); 

但是,請注意,

  • require是同步的,只讀取文件一次,下面的調用從緩存

  • 返回結果。如果你的文件不具有.json擴展,需要將不處理該文件的內容, JSON

+3

我想知道爲什麼我的require('file.json')一直在改變,直到我讀到這個 - 「require是同步的並且只有一次讀取文件,下面的調用從緩存中返回結果」。這可以通過刪除require.cache [require.resolve('file.json')]來繞過 –

1

如果在測試中處理JSON夾具,則使用node-fixtures

該項目將尋找一個名爲燈具必須是test目錄的孩子爲了加載所有的燈具(* .js文件或*以.json文件):

// test/fixtures/users.json 
{ 
    "dearwish": { 
    "name": "David", 
    "gender": "male" 
    }, 
    "innaro": { 
    "name": "Inna", 
    "gender": "female" 
    } 
} 
// test/users.test.js 
var fx = require('node-fixtures'); 
fx.users.dearwish.name; // => "David"