2017-02-17 76 views
0

在我的nodejs代码中,我目前发现有两种下载文件的方式,它们都可以工作,但使用不同的功能:下载或文件流。那么区别是什么呢?哪一个更好? :节点js下载vs文件流

app.get('/download', function(req, res, next){ 
    res.download("uploads/123.txt"); 
} 

app.get('/download', function(req, res, next){ 

    var file = __dirname + '/uploads/123.txt'; 
    var filestream = fs.createReadStream(file); 

    var mimetype = mime.lookup(file); 
    res.setheader('content-disposition', 'attachment; filename=' + '123.txt'); 
    res.setheader('content-type', mimetype); 

    filestream.pipe(res); 
}); 

回答

2

res.download是用快递使用的辅助函数。它使用sendFile(),它基本上使用第二个示例中的代码。所以无论你使用什么,引擎盖下发生的事情都是一样的。

因此,您只需使用res.download - 为什么要编写代码双倍...