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

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

问题描述

Expressjs 框架有一个 sendfile() 方法.如何在不使用整个框架的情况下做到这一点?

Expressjs framework has a sendfile() method. How can I do that without using the whole framework?

我正在使用 node-native-zip 创建存档,我想将其发送给用户.

I am using node-native-zip to create an archive and I want to send that to the user.

推荐答案

这是一个示例程序,它将通过从磁盘流式传输 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://优雅code.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

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

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