Javascript 如何读取json文件partycular with(js/node.js)
我想从json文件中读取用户列表,但我只想读取一个,因为我使用node.js fs模块`Javascript 如何读取json文件partycular with(js/node.js),javascript,json,node.js,Javascript,Json,Node.js,我想从json文件中读取用户列表,但我只想读取一个,因为我使用node.js fs模块` app.get("/1",function(req,res) {fs.readfile(“users.json”,function(data,err){res.write(data)}} 当有/1我想打开第一个用户,当/2第一次打开第二个用户时,将json加载到Serverstart上的RAM中,这样您就不必每次都重新读取: var users=JSON.parse(fs.readFileSync("us
app.get("/1",function(req,res)
{fs.readfile(“users.json”,function(data,err){res.write(data)}}
当有/1我想打开第一个用户,当/2第一次打开第二个用户时,将json加载到Serverstart上的RAM中,这样您就不必每次都重新读取:
var users=JSON.parse(fs.readFileSync("users.json","utf-8"));
现在,您可以使用Express功能:
//if theres a param ( a dynamic url) called user, lets place the user with that id into the property user of the request
app.param("user",function(req,res,next,id){
req.user=users[id];
next();
});
//if theres a request to user/1 the upper code will be executed with id=1, and well return our user
app.get("user/:user",function(req,res){
res.json(req.user);
});
请注意,使用param不是必需的,但是扩展程序更容易。现在您可以访问:
//localhost/user/1
上面的代码要求users.json为:
[
{name:test},
..
]
如果希望user/返回所有:
app.get("user/",function(req,res){
res.json(users);
});
fs.createReadstream(“users.json”).pipe(res);更好。还可以看看nodejs解析json