-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
82 lines (66 loc) · 1.72 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var Writable = require('stream').Writable;
var inherits = require('util').inherits;
var fs = require('fs');
var write = require('stream-write');
module.exports = DiskBuffer;
inherits(DiskBuffer, Writable);
var ids = 0;
function DiskBuffer(path, opts){
Writable.call(this);
opts = opts || {};
this._path = path;
this._id = ids++;
this._fileId = 0;
this._bytes = null;
this._writes = null;
this._flushBytes = opts.flushBytes || 0;
this._flushWrites = opts.flushWrites || 0;
this._ws = null;
this._filePath = null;
this._opened = null;
this._reset();
this._open();
}
DiskBuffer.prototype._reset = function(){
this._bytes = 0;
this._writes = 0;
};
DiskBuffer.prototype._open = function(){
this._filePath = this._pathname();
var ws = this._ws = fs.createWriteStream(this._filePath);
this._opened = new Date;
var onerror = this.emit.bind(this, 'error');
ws.on('error', onerror);
ws.on('open', function(){
ws.removeListener('error', onerror);
});
};
DiskBuffer.prototype._write = function(chunk, enc, done){
var self = this;
write(this._ws, chunk, function(err){
if (err) return done(err);
self._bytes += Buffer.byteLength(chunk);
self._writes++;
self._maybeFlush();
done();
});
};
DiskBuffer.prototype._flush = function(){
this._reset();
this.emit('flush', {
path: this._filePath,
opened: this._opened
});
this._open();
};
DiskBuffer.prototype._maybeFlush = function(){
if (this._flushBytes && this._bytes >= this._flushBytes) {
this._flush();
}
if (this._flushWrites && this._writes >= this._flushWrites) {
this._flush();
}
};
DiskBuffer.prototype._pathname = function(){
return [this._path, process.pid, this._id, this._fileId++].join('.');
};