3 var Transform = require("stream").Transform;
6 // == Exports ==================================================================
7 module.exports = function(iconv) {
9 // Additional Public API.
10 iconv.encodeStream = function encodeStream(encoding, options) {
11 return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
14 iconv.decodeStream = function decodeStream(encoding, options) {
15 return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
18 iconv.supportsStreams = true;
22 iconv.IconvLiteEncoderStream = IconvLiteEncoderStream;
23 iconv.IconvLiteDecoderStream = IconvLiteDecoderStream;
24 iconv._collect = IconvLiteDecoderStream.prototype.collect;
28 // == Encoder stream =======================================================
29 function IconvLiteEncoderStream(conv, options) {
31 options = options || {};
32 options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
33 Transform.call(this, options);
36 IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
37 constructor: { value: IconvLiteEncoderStream }
40 IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
41 if (typeof chunk != 'string')
42 return done(new Error("Iconv encoding stream needs strings as its input."));
44 var res = this.conv.write(chunk);
45 if (res && res.length) this.push(res);
53 IconvLiteEncoderStream.prototype._flush = function(done) {
55 var res = this.conv.end();
56 if (res && res.length) this.push(res);
64 IconvLiteEncoderStream.prototype.collect = function(cb) {
67 this.on('data', function(chunk) { chunks.push(chunk); });
68 this.on('end', function() {
69 cb(null, Buffer.concat(chunks));
75 // == Decoder stream =======================================================
76 function IconvLiteDecoderStream(conv, options) {
78 options = options || {};
79 options.encoding = this.encoding = 'utf8'; // We output strings.
80 Transform.call(this, options);
83 IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
84 constructor: { value: IconvLiteDecoderStream }
87 IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
88 if (!Buffer.isBuffer(chunk))
89 return done(new Error("Iconv decoding stream needs buffers as its input."));
91 var res = this.conv.write(chunk);
92 if (res && res.length) this.push(res, this.encoding);
100 IconvLiteDecoderStream.prototype._flush = function(done) {
102 var res = this.conv.end();
103 if (res && res.length) this.push(res, this.encoding);
111 IconvLiteDecoderStream.prototype.collect = function(cb) {
113 this.on('error', cb);
114 this.on('data', function(chunk) { res += chunk; });
115 this.on('end', function() {