Node.js发送文件作为响应

Node.js发送文件作为响应,第1张

Node.js发送文件作为响应

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

[更新] 正如@Aftershock在评论中所提到的,

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://elegantpre.com/2011/04/06/taking-baby-steps-with-node-js-pumping-
data-between-streams/



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5140357.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存