Skip to content

Instantly share code, notes, and snippets.

@alessioalex
Created November 22, 2014 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alessioalex/ca199dd705eef449ae17 to your computer and use it in GitHub Desktop.
Save alessioalex/ca199dd705eef449ae17 to your computer and use it in GitHub Desktop.
custom-writable-stream.js
// 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