Node.js发送文件作为响应 [英] Nodejs send file in response

查看:119
本文介绍了Node.js发送文件作为响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Expressjs框架具有sendfile()方法.我如何在不使用整个框架的情况下做到这一点.我正在使用node-native-zip创建档案,并将其发送给用户.

Expressjs framework has a sendfile() method. How can I do that without using a whole framework. I am using node-native-zip to create an archive and I want to send that to the user.

推荐答案

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

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[更新] 正如@Aftershock在评论中所提到的,util.pump不见了,并被Stream原型上的一种称为pipe的方法所代替;下面的代码反映了这一点.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

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/

这篇关于Node.js发送文件作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆