2012-10-03 115 views

回答

25
var fs = require("fs"), 
    json; 

function readJsonFileSync(filepath, encoding){ 

    if (typeof (encoding) == 'undefined'){ 
     encoding = 'utf8'; 
    } 
    var file = fs.readFileSync(filepath, encoding); 
    return JSON.parse(file); 
} 

function getConfig(file){ 

    var filepath = __dirname + '/' + file; 
    return readJsonFileSync(filepath); 
} 

//assume that config.json is in application root 

json = getConfig('config.json'); 
+10

這是一樣的'要求( './ config.json')' – Blowsie

+0

這是Node.js的版本比V0低有關。 5.x http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js – Brankodd

+3

'fs.readFile()'不同於'require()' 。如果你嘗試用'fs.readFile()'讀兩次文件,你會在內存中得到兩個不同的指針。但是如果你用相同的字符串require()',由於require()'的緩存行爲,你將指向內存中的同一個對象。這可能會導致意想不到的結果:修改第一個指針引用的對象意外更改第二個指針修改的對象。 – steampowered

11

這一個爲我工作。使用FS模塊:

var fs = require('fs'); 

function readJSONFile(filename, callback) { 
    fs.readFile(filename, function (err, data) { 
    if(err) { 
     callback(err); 
     return; 
    } 
    try { 
     callback(null, JSON.parse(data)); 
    } catch(exception) { 
     callback(exception); 
    } 
    }); 
} 

用法:

readJSONFile('../../data.json', function (err, json) { 
    if(err) { throw err; } 
    console.log(json); 
}); 

來源:https://codereview.stackexchange.com/a/26262

+0

我正在使用這一點,並得到'if(err){throw err; } SyntaxError:Unexpected token}' – Piet

14

做這樣的事情在你的控制器。

獲得JSON文件的內容:

ES5 var foo = require('path/to/your/file.json');

ES6 import foo from '/path/to/your/file.json';

發送JSON到您的視圖:

function getJson(req, res, next){ 
    res.send(foo); 
} 

這應該通過請求JSON內容發送到您的視圖。

注意

根據BTMPL

While this will work, do take note that require calls are cached and will return the same object on each subsequent call. Any change you make to the .json file when the server is running will not be reflected in subsequent responses from the server.

+0

請注意,對於本地文件,需要將前面的點/斜線附加到require。。/' –

相關問題