createReadStream().pipe()回调 [英] createReadStream().pipe() Callback

查看:86
本文介绍了createReadStream().pipe()回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,在这里我对createReadStream()有几个问题.

Sorry in advance, I have a couple of questions on createReadStream() here.

基本上,我正在做的是动态构建文件,并在完成后使用fs将其流式传输给用户.我正在使用.pipe()来确保节流正确(如果缓冲区已满,请停止读取,如果缓冲区未满,请重新开始,依此类推.)这是到目前为止我的代码示例.

Basically what I'm doing is dynamically building a file and streaming it to the user using fs once it is finished. I'm using .pipe() to make sure I'm throttling correctly (stop reading if buffer's full, start again once it's not, etc.) Here's a sample of my code I have so far.

http.createServer(function(req, res) {
  var stream = fs.createReadStream('<filepath>/example.pdf', {bufferSize: 64 * 1024})

  stream.pipe(res);

}).listen(3002, function() {
  console.log('Server listening on port 3002')
})

我读过另一个StackOverflow问题(对不起,丢了它),如果您使用常规的res.send()和res.end(),那么.pipe()效果很好,因为它称为.send和.end并增加限制.

I've read in another StackOverflow question (sorry, lost it) that if you're using the regular res.send() and res.end() that .pipe() works great, as it calls the .send and .end and adds throttling.

在大多数情况下都可以正常工作,除了我想在流完成后删除文件并且不使用.pipe()意味着我将不得不处理自己以获取回调.

That works fine for most cases, except I'm wanting to remove the file once the stream is complete and not using .pipe() means I'm going to have to handle throttling myself just to get a callback.

所以我猜测我想创建自己的假"res"对象,该对象具有.send()和.end()方法,它们执行res通常执行的操作,但是在.end()上执行我将添加其他代码来清理生成的文件.我的问题基本上是我该如何实现?

So I'm guessing that I'll want to create my own fake "res" object that has a .send() and .end() method that does what the res usually does, however on the .end() I'll put additional code to clean up the generated file. My question is basically how would I pull that off?

非常感谢您的帮助!

推荐答案

有关下载的第一部分可以通过

The first part about downloading can be answered by Download file from NodeJS Server.

关于在文件全部发送后删除文件,您只需添加自己的事件处理程序即可在文件发送完毕后删除文件.

As for removing the file after it has all been sent, you can just add your own event handler to remove the file once everything has been sent.

var stream = fs.createReadStream('<filepath>/example.pdf', {bufferSize: 64 * 1024})
stream.pipe(res);

var had_error = false;
stream.on('error', function(err){
  had_error = true;
});
stream.on('close', function(){
  if (!had_error) fs.unlink('<filepath>/example.pdf');
});

不需要 error 处理程序,但是如果您尝试发送文件时出错,则不要删除文件.

The error handler isn't 100% needed, but then you don't delete the file if there was an error while you were trying to send it.

这篇关于createReadStream().pipe()回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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