1 var Transform = require("stream").Transform;
4 // == Exports ==================================================================
5 module.exports = function(iconv) {
7 // Additional Public API.
8 iconv.encodeStream = function encodeStream(encoding, options) {
9 return new IconvLiteEncoderStream(iconv.getCodec(encoding).encoder(options), options);
12 iconv.decodeStream = function decodeStream(encoding, options) {
13 return new IconvLiteDecoderStream(iconv.getCodec(encoding).decoder(options), options);
16 iconv.supportsStreams = true;
20 iconv.IconvLiteEncoderStream = IconvLiteEncoderStream;
21 iconv.IconvLiteDecoderStream = IconvLiteDecoderStream;
22 iconv._collect = IconvLiteDecoderStream.prototype.collect;
26 // == Encoder stream =======================================================
27 function IconvLiteEncoderStream(conv, options) {
29 options = options || {};
30 options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
31 Transform.call(this, options);
34 IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
35 constructor: { value: IconvLiteEncoderStream }
38 IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
39 if (typeof chunk != 'string')
40 return done(new Error("Iconv encoding stream needs strings as its input."));
42 var res = this.conv.write(chunk);
43 if (res && res.length) this.push(res);
51 IconvLiteEncoderStream.prototype._flush = function(done) {
53 var res = this.conv.end();
54 if (res && res.length) this.push(res);
62 IconvLiteEncoderStream.prototype.collect = function(cb) {
65 this.on('data', function(chunk) { chunks.push(chunk); });
66 this.on('end', function() {
67 cb(null, Buffer.concat(chunks));
73 // == Decoder stream =======================================================
74 function IconvLiteDecoderStream(conv, options) {
76 options = options || {};
77 options.encoding = this.encoding = 'utf8'; // We output strings.
78 Transform.call(this, options);
81 IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
82 constructor: { value: IconvLiteDecoderStream }
85 IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
86 if (!Buffer.isBuffer(chunk))
87 return done(new Error("Iconv decoding stream needs buffers as its input."));
89 var res = this.conv.write(chunk);
90 if (res && res.length) this.push(res, this.encoding);
98 IconvLiteDecoderStream.prototype._flush = function(done) {
100 var res = this.conv.end();
101 if (res && res.length) this.push(res, this.encoding);
109 IconvLiteDecoderStream.prototype.collect = function(cb) {
111 this.on('error', cb);
112 this.on('data', function(chunk) { res += chunk; });
113 this.on('end', function() {