Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created November 28, 2012 00:40
Show Gist options
  • Save ishiduca/4158217 to your computer and use it in GitHub Desktop.
Save ishiduca/4158217 to your computer and use it in GitHub Desktop.
読み書き両用ストリームのひな形
// writeStreamとして受け取るデータは素通し
var stream = require('stream')
, util = require('util')
;
function DuplexStream () {
this.readable = true;
this.writable = true;
this.source;
this.on('pipe', function (src) { this.source = src }.bind(this));
}
util.inherits(DuplexStream, stream.Stream);
var dp = DuplexStream.prototype;
function write (data_, _enc) {
var data = data_;
if (Buffer.isBuffer(data)){
data = data.toString(_enc || 'utf8');
data = data.toUpperCase();
}
process.stdout.write(data);
}
dp.write = function (data_, _enc) {
write(data_, _enc);
this.emit('data', data_, _enc);
};
dp.end = function (data_, _enc) {
write(data_, _enc);
this.emit('end', data_, _enc);
};
dp.resume = function () { this.source && this.source.resume() };
dp.pause = function () { this.source && this.source.pause() };
module.exports = function () {
return new DuplexStream();
};
#!/usr/bin/env node
var dp = require('./dup');
var dpStream = dp();
var readStream = process.stdin;
var writeStream = process.stdout;
readStream.pipe(dpStream).pipe(writeStream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment