简体   繁体   English

为什么 Node.js 中的文件系统 (fs) 模块需要返回

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

I am learning node.js .我正在学习 node.js 。 I came across the below code in w3schools website.我在 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);

Can you please explain the significance of return in fs.readFile's callback function in the above code.能否请您解释一下上面代码中fs.readFile的回调函数中return的意义。 I tried with using return for res.end() and it still works normally.我尝试对 res.end() 使用 return ,但它仍然可以正常工作。

The return statement is not needed in this case, as res.end() is the last statement - it makes no difference.在这种情况下不需要return语句,因为res.end()是最后一个语句 - 它没有区别。 Consider this case however:但是,请考虑这种情况:

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

Here, in case of an error, we use return res.status(500).end() to make sure we do not execute any more code in that function and run into an "Headers have already been sent"-error.在这里,如果出现错误,我们使用return res.status(500).end()来确保我们不再在该函数中执行任何代码并遇到“Headers have been sent”错误。 You could of course use if/else and don't use return in case of an error, but I personally find the first option to be a bit cleaner.您当然可以使用if/else并且在出现错误时不要使用return ,但我个人认为第一个选项更简洁一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM