fs的事件createReadStream不总是被调用 [英] Events for fs createReadStream Not Always Being Called

查看:973
本文介绍了fs的事件createReadStream不总是被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个fs filestream用于提供动态创建的文件下载。我设置合适的标题后,获得此流并将其传递到我的响应对象。

I have an fs filestream being used to serve file downloads which are dynamically created. I get this stream and pipe it to my response object after setting appropriate headers.

我还设置了几个流事件,以便如果有错误或流结束,它从文件系统中删除生成的文件。

I also set a couple stream events so that if there's an error or the stream ends, it removes the generated files from the file system.

我遇到了一个问题,有时,当下载没有正确初始化或完成,可能有一些挂文件留在文件系统。我相信这是因为我挂钩到流中的事件。

I'm running into an issue where, on occasion, when the download isn't correctly initialized or finished there may be some hanging files left on the file system. I believe this is because of the events I hook into the stream.

我的代码:

stream = fs.createReadStream( fileName, {bufferSize: 64*1024})

had_error = false;
stream.on 'error', (err) ->
  had_error = err
stream.on 'close', ->
  if had_error
    console.log(had_error)

  fs.unlink fileName, (error) ->
    if error
      console.log("DELETE ERROR")
      console.log error

  fs.unlink dataFileName, (error) ->
    if error
      console.log("DELETE ERROR")
      console.log error


b $ b

检查流API 文档的关闭事件isn' t被所有流调用。我将使用'end'事件,但是根据文档:表示不再发生数据事件。如果流也是可写的,可以继续写。

Checking on the stream API documentation the 'close' event isn't called by all streams. I would use the 'end' event, however according to the docs: Indicates that no more 'data' events will happen. If the stream is also writable, it may be possible to continue writing.

我担心如果我使用'end'事件你可能遇到的问题,如果我删除这些文件,流并没有完成写入http响应,将导致损坏的下载。

I'm worried if I were to use the 'end' event could you run into the issue where if I remove these files and the stream isn't finished writing to the http response that it will lead to a corrupt download.

任何可靠事件可以用作捕获来删除这些文件,而不会中断下载?

Any "for sure" event that can be used as a catch to remove these files and not break downloads?

最差的情况我写一个cronjob来删除这些文件(bleh)。

Worst case scenario I write a cronjob to remove these files (bleh).

推荐答案

我从来没有找出确保事件被调用的确定方法。我想如果 response 对象从来没有真正启动流,它从不启动,从而从来没有结束事件。如果任何人知道一个解决方法,随时回答,并得到免费接受的答案。

I never did figure out a sure-fire way of ensuring the event gets called. I'm guessing that if the response object never actually starts the stream, it never starts thus never having an ending event. If anyone knows a workaround feel free to answer and get a free accepted answer.

这篇关于fs的事件createReadStream不总是被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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