3 var Buffer = require("buffer").Buffer,
4 Transform = require("stream").Transform;
7 // == Exports ==================================================================
8 module.exports = function(iconv) {
10 // Additional Public API.
11 iconv.encodeStream = function encodeStream(encoding, options) {
12 return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
15 iconv.decodeStream = function decodeStream(encoding, options) {
16 return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
19 iconv.supportsStreams = true;
23 iconv.IconvLiteEncoderStream = IconvLiteEncoderStream;
24 iconv.IconvLiteDecoderStream = IconvLiteDecoderStream;
25 iconv._collect = IconvLiteDecoderStream.prototype.collect;
29 // == Encoder stream =======================================================
30 function IconvLiteEncoderStream(conv, options) {
32 options = options || {};
33 options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
34 Transform.call(this, options);
37 IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
38 constructor: { value: IconvLiteEncoderStream }
41 IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
42 if (typeof chunk != 'string')
43 return done(new Error("Iconv encoding stream needs strings as its input."));
45 var res = this.conv.write(chunk);
46 if (res && res.length) this.push(res);
54 IconvLiteEncoderStream.prototype._flush = function(done) {
56 var res = this.conv.end();
57 if (res && res.length) this.push(res);
65 IconvLiteEncoderStream.prototype.collect = function(cb) {
68 this.on('data', function(chunk) { chunks.push(chunk); });
69 this.on('end', function() {
70 cb(null, Buffer.concat(chunks));
76 // == Decoder stream =======================================================
77 function IconvLiteDecoderStream(conv, options) {
79 options = options || {};
80 options.encoding = this.encoding = 'utf8'; // We output strings.
81 Transform.call(this, options);
84 IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
85 constructor: { value: IconvLiteDecoderStream }
88 IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
89 if (!Buffer.isBuffer(chunk))
90 return done(new Error("Iconv decoding stream needs buffers as its input."));
92 var res = this.conv.write(chunk);
93 if (res && res.length) this.push(res, this.encoding);
101 IconvLiteDecoderStream.prototype._flush = function(done) {
103 var res = this.conv.end();
104 if (res && res.length) this.push(res, this.encoding);
112 IconvLiteDecoderStream.prototype.collect = function(cb) {
114 this.on('error', cb);
115 this.on('data', function(chunk) { res += chunk; });
116 this.on('end', function() {