I've recently started to learn node.js and I have come across one of the chapters to get an idea about 'Upload files'. As you can see the code below( I've commented 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.IncomingForm();
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With