Created
November 29, 2012 01:18
-
-
Save coryvirok/4166081 to your computer and use it in GitHub Desktop.
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
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