Initial commit
[yaffs-website] / node_modules / fstream / lib / proxy-writer.js
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
8 module.exports = ProxyWriter
9
10 var Writer = require('./writer.js')
11 var getType = require('./get-type.js')
12 var inherits = require('inherits')
13 var collect = require('./collect.js')
14 var fs = require('fs')
15
16 inherits(ProxyWriter, Writer)
17
18 function ProxyWriter (props) {
19   var self = this
20   if (!(self instanceof ProxyWriter)) {
21     throw new Error('ProxyWriter must be called as constructor.')
22   }
23
24   self.props = props
25   self._needDrain = false
26
27   Writer.call(self, props)
28 }
29
30 ProxyWriter.prototype._stat = function () {
31   var self = this
32   var props = self.props
33   // stat the thing to see what the proxy should be.
34   var stat = props.follow ? 'stat' : 'lstat'
35
36   fs[stat](props.path, function (er, current) {
37     var type
38     if (er || !current) {
39       type = 'File'
40     } else {
41       type = getType(current)
42     }
43
44     props[type] = true
45     props.type = self.type = type
46
47     self._old = current
48     self._addProxy(Writer(props, current))
49   })
50 }
51
52 ProxyWriter.prototype._addProxy = function (proxy) {
53   // console.error("~~ set proxy", this.path)
54   var self = this
55   if (self._proxy) {
56     return self.error('proxy already set')
57   }
58
59   self._proxy = proxy
60   ;[
61     'ready',
62     'error',
63     'close',
64     'pipe',
65     'drain',
66     'warn'
67   ].forEach(function (ev) {
68     proxy.on(ev, self.emit.bind(self, ev))
69   })
70
71   self.emit('proxy', proxy)
72
73   var calls = self._buffer
74   calls.forEach(function (c) {
75     // console.error("~~ ~~ proxy buffered call", c[0], c[1])
76     proxy[c[0]].apply(proxy, c[1])
77   })
78   self._buffer.length = 0
79   if (self._needsDrain) self.emit('drain')
80 }
81
82 ProxyWriter.prototype.add = function (entry) {
83   // console.error("~~ proxy add")
84   collect(entry)
85
86   if (!this._proxy) {
87     this._buffer.push(['add', [entry]])
88     this._needDrain = true
89     return false
90   }
91   return this._proxy.add(entry)
92 }
93
94 ProxyWriter.prototype.write = function (c) {
95   // console.error('~~ proxy write')
96   if (!this._proxy) {
97     this._buffer.push(['write', [c]])
98     this._needDrain = true
99     return false
100   }
101   return this._proxy.write(c)
102 }
103
104 ProxyWriter.prototype.end = function (c) {
105   // console.error('~~ proxy end')
106   if (!this._proxy) {
107     this._buffer.push(['end', [c]])
108     return false
109   }
110   return this._proxy.end(c)
111 }