2012-10-03 48 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。。/' –

相关问题