create-output-stream.js 960 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var path = require('path')
  2. var fs = require('fs')
  3. var mkdir = require('../mkdirs')
  4. var WriteStream = fs.WriteStream
  5. function createOutputStream (file, options) {
  6. var dirExists = false
  7. var dir = path.dirname(file)
  8. options = options || {}
  9. // if fd is set with an actual number, file is created, hence directory is too
  10. if (options.fd) {
  11. return fs.createWriteStream(file, options)
  12. } else {
  13. // this hacks the WriteStream constructor from calling open()
  14. options.fd = -1
  15. }
  16. var ws = new WriteStream(file, options)
  17. var oldOpen = ws.open
  18. ws.open = function () {
  19. ws.fd = null // set actual fd
  20. if (dirExists) return oldOpen.call(ws)
  21. // this only runs once on first write
  22. mkdir.mkdirs(dir, function (err) {
  23. if (err) {
  24. ws.destroy()
  25. ws.emit('error', err)
  26. return
  27. }
  28. dirExists = true
  29. oldOpen.call(ws)
  30. })
  31. }
  32. ws.open()
  33. return ws
  34. }
  35. module.exports = createOutputStream