如何获得JSON文件,并在视图中显示
在快速获取.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 发送到您的视图:
function getJson(req, res, next){ res.send(foo); }
这应该通过请求发送json内容到你的视图。
注意
根据BTMPL
虽然这将起作用,但请注意,要求调用被caching,并将在每个后续调用中返回相同的对象。 服务器运行时对.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); });
来源: https : //codereview.stackexchange.com/a/26262