2012-10-03 29 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

によれば、これは 'これはV0より低いバージョンのNode.jsに関連していた( './ config.json')' – Blowsie

+0

を必要と同様です。 5.x http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js – Brankodd

+3

'fs.readFile()'は 'require()'と同じではありません。 。 'fs.readFile()'でファイルを2回読むと、メモリ内に2つの異なるポインタが得られます。しかし、同じ文字列で 'require()'を実行すると、 'required()'のキャッシュ動作のためにメモリ内の同じオブジェクトを指します。これにより、予期せず第1ポインタによって参照されるオブジェクトを変更すると、第2ポインタによって変更されたオブジェクトが予期せず変更されるという予期せぬ結果が生じる可能性があります。 – 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:予期しないトークン} ' – 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

ローカルファイルの場合、必要な'。/ 'の後ろに先行するドット/スラッシュが必要であることに注意してください。 –

関連する問題