javascript - Why and when do we use response.end() and return response.end() in node.js? - Stack Overflow

I've recently started to learn node.jsand I have e across one of the chapters to get an idea abo

I've recently started to learn node.js and I have e across one of the chapters to get an idea about 'Upload files'. As you can see the code below( I've mented over the line where i have doubt), is it necessary to write "return res.end();" because "res.end();" gives the output. So, here arises the question, like, when, why and where do we use 'return' keyword along with 'res.end()'.

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
var mv = require('mv');

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IningForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
      mv(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post"  enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();//       <------------HERE
  }
}).listen(8080); 

I've recently started to learn node.js and I have e across one of the chapters to get an idea about 'Upload files'. As you can see the code below( I've mented over the line where i have doubt), is it necessary to write "return res.end();" because "res.end();" gives the output. So, here arises the question, like, when, why and where do we use 'return' keyword along with 'res.end()'.

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
var mv = require('mv');

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IningForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
      mv(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post"  enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();//       <------------HERE
  }
}).listen(8080); 
Share Improve this question asked Dec 19, 2017 at 6:52 user6894700user6894700 431 gold badge1 silver badge6 bronze badges 3
  • 1 It's a short way to write res.end(); return;. There is no return value from end() IIRC, and the value you return in the request listener is ignored anyway. – Ry- Commented Dec 19, 2017 at 6:54
  • "I have e across one of the chapters to get an idea about 'Upload files'." - which book are you reading? – Bergi Commented Dec 19, 2017 at 7:06
  • Hi Bergi, well, in fact, it's not the book as such but its the tutorials from w3schools and under the nodejs tutorials es this topic. – user6894700 Commented Dec 19, 2017 at 8:12
Add a ment  | 

1 Answer 1

Reset to default 4

The return in return res.end(); is only for code flow control to exit the function and not execute any more code in that function. The server that calls your request handler callback does not pay any attention to a return value so the code is not trying to return a value. It's just to stop any further execution in the function.

In the specific context you show where res.end() is on the last line of the function, there is NO functional difference at all between res.end() and return res.send().

In some other contexts, there might be some other code that could still execute later in the function and return is one way to keep that code from executing. return res.end() is sometimes used as a shortcut to avoid an else clause as in something like this:

 if (err) {
     return res.status(500).end();
 }
 // other code here for non-error case

Instead of doing this:

 if (err) {
     res.status(500).end();
 } else {
    // other code here for non-error case
 }

Both of those are functionally the same. The return in the first is used as a shortcut to avoid the else in the second (not personally my favorite coding style, but a legit choice if desired).


FYI, in that code you show, the if (err) throw err; inside an async callback is almost never the proper way to do error handling because the exception goes into some async infrastructure where you can't catch it or do anything intelligent with it. I know your question wasn't about this, but since you're learning node.js, I thought I'd point this out. In this particular case, you should probably send the client a 5xx error status.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744274208a4566249.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信