Skip to content

Instantly share code, notes, and snippets.

@coryvirok
Created November 29, 2012 01:18
Show Gist options
  • Save coryvirok/4166081 to your computer and use it in GitHub Desktop.
Save coryvirok/4166081 to your computer and use it in GitHub Desktop.
var eventstream = require('event-stream');
var fs = require('fs');
// creates a new write stream on first write() call
exports.createLazyWriteStream = function(wsFactory) {
var Stream = require('stream');
var s = new Stream;
var ws;
s.writable = true;
s.write = function(buf) {
if (!ws) {
console.log('creating ws');
ws = wsFactory();
var self = this;
ws.on('drain', function() { self.emit('drain'); });
ws.on('error', function(err) { self.emit('error', err); });
ws.on('close', function() { self.emit('close'); });
ws.on('pipe', function(src) { self.emit('pipe', src); });
}
console.log('> ' + buf);
return ws.write(buf);
};
s.end = function(buf) {
if (arguments.length) {
s.write(buf);
}
s.writable = false;
if (ws) {
ws.end();
}
};
s.destroy = function () {
s.writable = false;
if (ws) {
ws.destroy();
}
};
return s;
};
var s = exports.createLazyWriteStream(function() {
return fs.createWriteStream('./tmp.data', {flags: 'a'});
});
s.on('close', function() {
console.log('closed... done');
});
console.log('writing');
setTimeout(function() {
s.write('oh hai');
}, 5000);
console.log('ending');
s.end();
console.log('done');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment