forked from AndreasMadsen/newlinepoint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewlinepoint.js
48 lines (37 loc) · 1.11 KB
/
newlinepoint.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
var util = require('util');
var stream = require('stream');
var CRLF = /\r?\n/g,
CR = /\r/g;
function Linepoint(chars) {
if (!(this instanceof Linepoint)) return new Linepoint(chars);
stream.Transform.call(this);
if (typeof chars !== 'string') {
throw new Error('first argument must be a string');
}
this._chars = chars;
this._lastCR = '';
}
module.exports = Linepoint;
util.inherits(Linepoint, stream.Transform);
Linepoint.prototype._transform = function (chunk, encodeing, done) {
chunk = this._lastCR + chunk.toString();
chunk = chunk.replace(CRLF, this._chars);
chunk = chunk.replace(CR, this._chars);
// If the last char is \r then it might be followed by a \n char
// so hold that char back and use it in the next chunk
if (chunk.charCodeAt(chunk.length - 1) === 13) {
this._lastCR = '\r';
this.push(chunk.slice(0, -1));
} else {
this._lastCR = '';
this.push(chunk);
}
done(null);
};
// End of stream, output \r if stream ended with that char
Linepoint.prototype._flush = function (done) {
if (this._lastCR) {
this.push(this._lastCR);
}
done(null);
};