NodeJS-以节流速度提供文件 [英] NodeJS - Serve file with throttled speed

查看:167
本文介绍了NodeJS-以节流速度提供文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对NodeJS很陌生,正在尝试其他东西.

I'm quite new to NodeJS and trying different stuff.

我所能做的就是使用以下代码下载正在运行的文件:

What I was able to do is to download a file going using the following code:

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


  var file = 'public/songs/myfile.mp3';

  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);
  res.setHeader('Content-Length', file.length);

  var filestream = fs.createReadStream(file);

  filestream.pipe(res);
});

这很好用,现在我要达到的目标是看看是否有可能限制下载速度.就像有人尝试下载文件一样,它将以最大1 Mbps的速度下载(例如).

This works well, now what I'm trying to achive is see if it's possible to throttle the download speed. Like if someone tries to download the file it will download at max 1 Mbps (for example).

我尝试使用此代码: https://gist.github.com/4poc/1454516

当我加载页面时,它似乎不确定地加载,但是我认为问题出在

When I load the page it seems to load indefinetly, but I think that the problem is

filestream.pipe(limitStream);

因为没有响应.

如何实现我想做的事情?或者如何修复我尝试使用的代码?

推荐答案

reqres对象是流,因此可以通过管道传递响应:

The req and res objects are streams, so you can pipe on the response:

var filestream = fs.createReadStream(file);

filestream.pipe(limitStream).pipe(res);

fwow:每次调用pipe()时,您都会返回一个新的流.上面是这样的:

fwiw: every time you call pipe() you get back a new stream. The above is the same as this:

var filestream = fs.createReadStream(file);

var throttleStream = filestream.pipe(limitStream);

throttleStream.pipe(res);

了解这一点很重要,因为它很诱人,但是却无法实现您的期望:

This is important to understand because it's tempting to do this, but it won't do what you expect:

var filestream = fs.createReadStream(file);

filestream.pipe(limitStream);

filestream.pipe(res);

这篇关于NodeJS-以节流速度提供文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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