Bra*_*odd 28
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');
Run Code Online (Sandbox Code Playgroud)
CEN*_*EDE 22
在你的控制器中做这样的事情.
为了获得该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);
}
Run Code Online (Sandbox Code Playgroud)
这应该通过请求将json内容发送到您的视图.
注意
根据BTMPL
虽然这可以工作,但请注意,要求调用被缓存,并在每次后续调用时返回相同的对象.在服务器运行时对.json文件所做的任何更改都不会反映在服务器的后续响应中.
Arb*_*ong 13
这个对我有用.使用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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
用法:
readJSONFile('../../data.json', function (err, json) {
if(err) { throw err; }
console.log(json);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46872 次 |
| 最近记录: |