Created
November 22, 2014 12:47
-
-
Save alessioalex/ca199dd705eef449ae17 to your computer and use it in GitHub Desktop.
custom-writable-stream.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// example from http://codewinds.com/blog/2013-08-19-nodejs-writable-streams.html | |
"use strict"; | |
var stream = require('stream'); | |
var util = require('util'); | |
// use Node.js Writable, otherwise load polyfill | |
var Writable = stream.Writable; | |
var memStore = { }; | |
/* Writable memory stream */ | |
function WMStrm(key, options) { | |
// allow use without new operator | |
if (!(this instanceof WMStrm)) { | |
return new WMStrm(key, options); | |
} | |
Writable.call(this, options); // init super | |
this.key = key; // save key | |
memStore[key] = new Buffer(''); // empty | |
} | |
util.inherits(WMStrm, Writable); | |
WMStrm.prototype._write = function (chunk, enc, cb) { | |
// our memory store stores things in buffers | |
var buffer = (Buffer.isBuffer(chunk)) ? | |
chunk : // already is Buffer use it | |
new Buffer(chunk, enc); // string, convert | |
// concat to the buffer already there | |
memStore[this.key] = Buffer.concat([memStore[this.key], buffer]); | |
cb(); | |
}; | |
// Trying our stream out | |
var wstream = new WMStrm('foo'); | |
wstream.on('finish', function () { | |
console.log('finished writing'); | |
console.log('value is:', memStore.foo.toString()); | |
}); | |
wstream.write('hello '); | |
wstream.write('world'); | |
wstream.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment