2017-10-16 22 views
0

目前我正在試圖讓我的middeware寫JSON數據被記錄在後一個文件中。我的問題是,每當我執行功能,沒有被寫入文件,也沒有輸出在控制檯中。NodeJS不寫入文件。中間件不工作

我用這個問題爲例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!"); 
     } 
    } 

我想先與蒙戈查詢它來寫用戶名日期到文件:dbx.accounts.findOne(function(err, info)

爲什麼我的中間件沒有按照假設寫入json文件?

編輯:

我已經把return聲明是這樣的:

fs.readFile( 'logs.json', 'utf-8',功能readFileCallback(ERR,數據){

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 
     }}); 

,但它仍然沒有寫入文件。

+1

您返回從你函數'達到其寫在你的文件中的代碼之前返回info'。 – ricky

+0

是的,函數終止* *返回* – turmuka

+0

我應該在哪裏放置它?我只是把它放在'if'語句之後,它仍然沒有寫入。 – ZombieChowder

回答

0

首先感謝所有關於這個問題的幫助下,我圖從你們那裏得到了很多幫助,從而發現了錯誤。

我完全清除return info發言,因爲我並不真的需要它。 其次我刪除了obj = JSON.parse(obj),因爲它已經由JavaScript解釋器解析。我還刪除了JSON.stringify(輸出),因爲我沒有在任何地方使用輸出。

感謝您的幫助和抱歉,如果我帶來任何困擾。