[英]NodeJS not writing to file. Middleware not working
我當前正在嘗試使我的中間件在登錄后將json數據寫入文件。我的問題是,每當我執行該函數時 ,都不會寫入文件或在控制台中輸出任何內容。
我以這個問題為例例子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查詢來將用戶名和日期寫入文件: dbx.accounts.findOne(function(err, info)
為什么我的中間件沒有按預期寫入json文件?
編輯:
我將return
語句像這樣:
fs.readFile('logs.json','utf8',函數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
聲明,因此我將其完全刪除。 其次,我刪除了obj = JSON.parse(obj)
因為javascript解釋器已經對其進行了解析 。 我還刪除了JSON.stringify(output),因為我沒有在任何地方使用輸出。
感謝您的幫助,如果造成任何混亂,我們深表歉意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.