I am currently trying to make my middeware write json data to a file after is logged in. My issue is that whenever I execute the function, nothing gets written to the file nor output in the console.
I've used this question as an example Example 1 but still nothing works.
Here is the middleware part of my NodeJS script:
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!");
}
}
I am trying to write username and date to the file by querying it with Mongo first: dbx.accounts.findOne(function(err, info)
Why is my middleware not writing to the json file as supposed?
EDIT:
I've put the return
statement like this:
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
}});
but it still doesn't write to the file.