Expressで.json
ファイルを取得し、ビューに表示する際に問題があります。あなたの例を親切に教えてください。
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');
このようなことをコントローラーで行ってください。
jsonファイルの内容を取得**します.
ES5
var foo = require('path/to/your/file.json');
.
ES6
import foo from '/path/to/your/file.json'
;
ビューに json を send する。
function getJson(req, res, next){
res.send(foo);
}
これは、json コンテンツをリクエスト経由でビューに送信するものです。
**注意
BTMPL](https://stackoverflow.com/users/1008329/btmpl)による。
これは動作しますが、requireの呼び出しはキャッシュされ、以降の呼び出しで同じオブジェクトが返されることに注意してください。サーバーの実行中に .json ファイルを変更しても、その後のサーバーからの応答には反映されません。
これは私の場合、うまくいきました。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);
});
[出典][1]