Events for fs createReadStream Not Always Being Called

試著忘記壹切 提交于 2019-12-11 23:19:52

问题


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.

My code:

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

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.

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?

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


回答1:


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.



来源:https://stackoverflow.com/questions/15163567/events-for-fs-createreadstream-not-always-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!