问题
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