proxy-reader.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // A reader for when we don't yet know what kind of thing
  2. // the thing is.
  3. module.exports = ProxyReader
  4. var Reader = require('./reader.js')
  5. var getType = require('./get-type.js')
  6. var inherits = require('inherits')
  7. var fs = require('graceful-fs')
  8. inherits(ProxyReader, Reader)
  9. function ProxyReader (props) {
  10. var self = this
  11. if (!(self instanceof ProxyReader)) {
  12. throw new Error('ProxyReader must be called as constructor.')
  13. }
  14. self.props = props
  15. self._buffer = []
  16. self.ready = false
  17. Reader.call(self, props)
  18. }
  19. ProxyReader.prototype._stat = function () {
  20. var self = this
  21. var props = self.props
  22. // stat the thing to see what the proxy should be.
  23. var stat = props.follow ? 'stat' : 'lstat'
  24. fs[stat](props.path, function (er, current) {
  25. var type
  26. if (er || !current) {
  27. type = 'File'
  28. } else {
  29. type = getType(current)
  30. }
  31. props[type] = true
  32. props.type = self.type = type
  33. self._old = current
  34. self._addProxy(Reader(props, current))
  35. })
  36. }
  37. ProxyReader.prototype._addProxy = function (proxy) {
  38. var self = this
  39. if (self._proxyTarget) {
  40. return self.error('proxy already set')
  41. }
  42. self._proxyTarget = proxy
  43. proxy._proxy = self
  44. ;[
  45. 'error',
  46. 'data',
  47. 'end',
  48. 'close',
  49. 'linkpath',
  50. 'entry',
  51. 'entryEnd',
  52. 'child',
  53. 'childEnd',
  54. 'warn',
  55. 'stat'
  56. ].forEach(function (ev) {
  57. // console.error('~~ proxy event', ev, self.path)
  58. proxy.on(ev, self.emit.bind(self, ev))
  59. })
  60. self.emit('proxy', proxy)
  61. proxy.on('ready', function () {
  62. // console.error("~~ proxy is ready!", self.path)
  63. self.ready = true
  64. self.emit('ready')
  65. })
  66. var calls = self._buffer
  67. self._buffer.length = 0
  68. calls.forEach(function (c) {
  69. proxy[c[0]].apply(proxy, c[1])
  70. })
  71. }
  72. ProxyReader.prototype.pause = function () {
  73. return this._proxyTarget ? this._proxyTarget.pause() : false
  74. }
  75. ProxyReader.prototype.resume = function () {
  76. return this._proxyTarget ? this._proxyTarget.resume() : false
  77. }