【发布时间】:2017-10-16 06:35:42
【问题描述】:
我目前正在尝试让我的中间件在登录后将 json 数据写入文件。我的问题是,每当我执行 函数 时,都不会写入文件,也不会在控制台中输出.
我以这个问题为例Example 1 但仍然没有任何效果。
这是我的 NodeJS 脚本的中间件部分:
function isLoggedIn(req, res, next) {
dbx.accounts.findOne(function(err, info){
console.log(JSON.stringify(info.username));
return info;
var xx = info.username;
var date = new Date();
console.log(JSON.stringify(date));
var obj = {
users: []
};
fs.readFile('logs.json', 'utf8', function readFileCallback(err, data){
console.log(JSON.stringify(obj));
obj.users.push({time: date, name: xx});
if (err){
console.log(err);
} else {
obj = JSON.parse( ); //now it an object
obj.users.push({time: date, name: xx}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFileSync('logs.json', json, 'utf8', JSON.stringify(output)); // write it back
}});
});
//logs.stamps.push({id:----, timestamp:date.toString()})
console.log('here is Authenticated', req.isAuthenticated()) //prints out 'here is Authenticated' if the Passport login is successful
if (req.isAuthenticated()){
return next();
}else{
console.log("routes Print log You Cannot Log in!");
}
}
我正在尝试通过首先使用 Mongo 查询将 username 和 date 写入文件:dbx.accounts.findOne(function(err, info)
为什么我的中间件没有按预期写入 json 文件?
编辑:
我将return 声明如下:
fs.readFile('logs.json', 'utf8', function readFileCallback(err, data){
console.log(JSON.stringify(obj));
obj.users.push({time: date, name: xx});
if (err){
console.log(err);
} else {
obj = JSON.parse( ); //now it an object
obj.users.push({time: date, name: xx}); //add some data
json = JSON.stringify(obj); //convert it back to json
return info;
fs.writeFileSync('logs.json', json, 'utf8', JSON.stringify(output)); // write it back
}});
但它仍然没有写入文件。
【问题讨论】:
-
在到达写入文件的代码之前,您正在从函数
return info返回。 -
是的,函数在
return终止 -
我应该把它放在哪里?我只是把它放在
if语句之后,它仍然不写。 -
更新你的代码你最近尝试了什么
-
@ricky 我已经更新了我的问题。
标签: javascript json node.js express