簡體   English   中英

如何使用回調函數修復錯誤?

[英]How do I fix an error with a callback function?

我正在嘗試開發一個應用程序,以幫助用戶根據他們回答的某些問題找到朋友。 當代碼到達文件的第46行時,我不斷出現一個錯誤,提示“ TypeError [ERR_INVALID_CALLBACK]:回調必須是一個函數”,它使用fs更改另一個文件的內容以添加用戶輸入的信息在此應用程序的網頁上,我不知道為什么要這樣做。

const fs = require('fs');

module.exports = function(app, path) {

    app.get('api/friends', function(req, res) {
        fs.readFile("app/data/friends.js", "utf8", function(err, data) {
            if (err) throw err;

            else {
                res.json(JSON.parse(data));
            }
        });
    });

    app.post('/api/friends', function(req, res) {
        let results = [];

        const postResponse = JSON.stringify(req.body);

        fs.readFile('app/data/friends.js', function (err, data) {
            if (err) throw err; 

            let friendFile = JSON.parse(data);
            console.log(friendFile[0].answers);
            let closestMatch = 0;
            let matchScore = 999999999999999;

            for (let i = 0; i < friendFile.length; i++) {
                console.log(friendFile.length);
                let spaceBetween = 0;
                for (let j = 0; j < friendFile[i].answers.length; j++) {
                    // ['answers[]'][j]
                    console.log(req.body.answers[j]);
                    spaceBetween += Math.abs((parseInt(req.body.answers[j]) - parseInt(friendFile[i].answers[j])));
                }
                if (spaceBetween <= matchScore) {
                    matchScore = spaceBetween;
                    closestMatch == i;
                } 
            }

            results.push(friendFile[closestMatch]);

            friendFile.push(JSON.parse(postResponse));

            fs.writeFile("app/data/friends.js", JSON.stringify(friendFile));
                res.send(results[0]);
        })
    })
}

我希望這樣可以編輯friends.js文件,以添加用戶在調查中給出的回復中的所有信息,並根據用戶給出的答案將用戶最親密的朋友匹配發布到頁面上。

只需在調用writeFile時添加回調函數

let callback = function(err) {
 if (err) throw err;
  console.log('The file has been saved!');
};
fs.writeFile("app/data/friends.js", JSON.stringify(friendFile), callback);

我猜這是一個快遞應用程序,是嗎? 只是改變..

fs.writeFile("app/data/friends.js", JSON.stringify(friendFile));

...至...

fs.writeFile("app/data/friends.js", JSON.stringify(friendFile), function (err) {
  if (err) {
    res.sendStatus(500) // Let the client know we died
    throw err; // Or do something else.
  }

  // If you want to add something for after the file is written to disk put it here.
  // Code execution won't reach this point if the error above throws.
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM