簡體   English   中英

為什么 Node.js 中的文件系統 (fs) 模塊需要返回

[英]Why return is required in file system (fs) module in Node.js

我正在學習 node.js 。 我在 w3schools 網站上遇到了以下代碼。

    var http = require('http');
    var fs = require('fs');
    http.createServer(function (req, res) {
      fs.readFile('demofile1.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        **return** res.end();
      });

}).listen(8080);

能否請您解釋一下上面代碼中fs.readFile的回調函數中return的意義。 我嘗試對 res.end() 使用 return ,但它仍然可以正常工作。

在這種情況下不需要return語句,因為res.end()是最后一個語句 - 它沒有區別。 但是,請考慮這種情況:

fs.readFile('demofile1.html', function(err, data) {
        if(err) {
          return res.status(500).end();
        }
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.end();
});

在這里,如果出現錯誤,我們使用return res.status(500).end()來確保我們不再在該函數中執行任何代碼並遇到“Headers have been sent”錯誤。 您當然可以使用if/else並且在出現錯誤時不要使用return ,但我個人認為第一個選項更簡潔一些。

暫無
暫無

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

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