proxy-writer.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // A writer for when we don't know what kind of thing
  2. // the thing is. That is, it's not explicitly set,
  3. // so we're going to make it whatever the thing already
  4. // is, or "File"
  5. //
  6. // Until then, collect all events.
  7. module.exports = ProxyWriter
  8. var Writer = require("./writer.js")
  9. , getType = require("./get-type.js")
  10. , inherits = require("inherits")
  11. , collect = require("./collect.js")
  12. , fs = require("fs")
  13. inherits(ProxyWriter, Writer)
  14. function ProxyWriter (props) {
  15. var me = this
  16. if (!(me instanceof ProxyWriter)) throw new Error(
  17. "ProxyWriter must be called as constructor.")
  18. me.props = props
  19. me._needDrain = false
  20. Writer.call(me, props)
  21. }
  22. ProxyWriter.prototype._stat = function () {
  23. var me = this
  24. , props = me.props
  25. // stat the thing to see what the proxy should be.
  26. , stat = props.follow ? "stat" : "lstat"
  27. fs[stat](props.path, function (er, current) {
  28. var type
  29. if (er || !current) {
  30. type = "File"
  31. } else {
  32. type = getType(current)
  33. }
  34. props[type] = true
  35. props.type = me.type = type
  36. me._old = current
  37. me._addProxy(Writer(props, current))
  38. })
  39. }
  40. ProxyWriter.prototype._addProxy = function (proxy) {
  41. // console.error("~~ set proxy", this.path)
  42. var me = this
  43. if (me._proxy) {
  44. return me.error("proxy already set")
  45. }
  46. me._proxy = proxy
  47. ; [ "ready"
  48. , "error"
  49. , "close"
  50. , "pipe"
  51. , "drain"
  52. , "warn"
  53. ].forEach(function (ev) {
  54. proxy.on(ev, me.emit.bind(me, ev))
  55. })
  56. me.emit("proxy", proxy)
  57. var calls = me._buffer
  58. calls.forEach(function (c) {
  59. // console.error("~~ ~~ proxy buffered call", c[0], c[1])
  60. proxy[c[0]].apply(proxy, c[1])
  61. })
  62. me._buffer.length = 0
  63. if (me._needsDrain) me.emit("drain")
  64. }
  65. ProxyWriter.prototype.add = function (entry) {
  66. // console.error("~~ proxy add")
  67. collect(entry)
  68. if (!this._proxy) {
  69. this._buffer.push(["add", [entry]])
  70. this._needDrain = true
  71. return false
  72. }
  73. return this._proxy.add(entry)
  74. }
  75. ProxyWriter.prototype.write = function (c) {
  76. // console.error("~~ proxy write")
  77. if (!this._proxy) {
  78. this._buffer.push(["write", [c]])
  79. this._needDrain = true
  80. return false
  81. }
  82. return this._proxy.write(c)
  83. }
  84. ProxyWriter.prototype.end = function (c) {
  85. // console.error("~~ proxy end")
  86. if (!this._proxy) {
  87. this._buffer.push(["end", [c]])
  88. return false
  89. }
  90. return this._proxy.end(c)
  91. }