I would like to pipe a node.js stream into an output file. But I would also like to make sure that output destination exists before I start piping. The problem with the following code is that event handlers from pipe are added late (after assurePath
callback is called) so data is not available anymore in the input stream. I would not like to use sync fs methods to not block the whole process.
assurePath = (path, callback) ->
path = path.split path.sep
i = 0
async.eachSeries path[1...path.length-1], (segment, callback) =>
i++
p = path[0..i].join path.sep
fs.exists p, (exists) =>
return callback() if exists
fs.mkdir p, callback
,
callback
saveStream = (filename, stream, callback) ->
path = fullPath filename
assurePath path, (error) ->
return callback error if error
finished = false
stream.on('error', (error) ->
return if finished
finished = true
callback error
).pipe(
fs.createWriteStream path
).on('finish', ->
return if finished
finished = true
callback()
).on('error', (error) ->
return if finished
finished = true
callback error
)
You can try pausing your stream right before calling assurePath
and then resuming it in callback:
saveStream = (filename, stream, callback) ->
stream.pause()
path = fullPath filename
assurePath path, (error) ->
stream.resume()
# ...
Calling .pause()
will cause your stream
to stop emitting data events. Any data that becomes available will remain in the internal buffer. Calling .resume()
in assurePath
callback will cause your stream
to resume emitting data events.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments