Nodejs发送文件作为回应

Expressjs框架有一个sendfile()方法。 我怎样才能做到这一点,而不使用整个框架。 我正在使用node-native-zip来创build一个存档,我想将其发送给用户。

下面是一个示例程序,它将通过从磁盘传输myfile.mp3(也就是说,在发送文件之前不会将整个文件读入内存)。 服务器侦听端口2000。

[更新]正如@Aftershock在评论中所提到的, util.pump已经util.pump存在了,并且被Stream原型中的一个方法所取代,名为pipe ; 下面的代码反映了这一点。

 var http = require('http'), fileSystem = require('fs'), path = require('path'); http.createServer(function(request, response) { var filePath = path.join(__dirname, 'myfile.mp3'); var stat = fileSystem.statSync(filePath); response.writeHead(200, { 'Content-Type': 'audio/mpeg', 'Content-Length': stat.size }); var readStream = fileSystem.createReadStream(filePath); // We replaced all the event handlers with a simple call to readStream.pipe() readStream.pipe(response); }) .listen(2000); 

取自http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

您需要使用Stream来发送文件(存档)作为响应,您还需要在响应头中使用适当的Content-type。

有一个示例函数可以做到这一点:

 const fs = require('fs'); // Where fileName is name of the file and response is Node.js Reponse. responseFile = (fileName, response) => { const filePath = "/path/to/archive.rar" // or any file format // Check if file specified by the filePath exists fs.exists(filePath, function(exists){ if (exists) { // Content-type is very interesting part that guarantee that // Web browser will handle response in an appropriate manner. response.writeHead(200, { "Content-Type": "application/octet-stream", "Content-Disposition": "attachment; filename=" + fileName }); fs.createReadStream(filePath).pipe(response); } else { response.writeHead(400, {"Content-Type": "text/plain"}); response.end("ERROR File does not exist"); } }); } } 

Content-Type字段的目的是完整地描述包含在主体中的数据,以便接收用户代理可以select合适的代理或机制来向用户呈现数据,或以适当的方式处理数据。

“application / octet-stream”在RFC 2046中被定义为“任意二进制数据”,这个内容types的目的是保存到磁盘 – 这是你真正需要的。

“文件名= [文件名称]”指定将被下载的文件的名称。

有关更多信息,请参阅此stackoverflow主题 。