Skip to content

Instantly share code, notes, and snippets.

@snowmantw
Last active April 10, 2016 16:40
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 snowmantw/814ccd38214bd1a3d0193b41a8fa7a71 to your computer and use it in GitHub Desktop.
Save snowmantw/814ccd38214bd1a3d0193b41a8fa7a71 to your computer and use it in GitHub Desktop.
// This would provide `createFile`, `createReadStream`, `writeContent` and `createWriteStream`.
var FileSystem = require('FileSystem');
var Reader = function() {
this.counter = 0;
};
Reader.prototype = FileSystem.prototype;
Reader.prototype.paths = ['/tmp/urandom-1.txt', '/tmp/urandom-2.txt'];
Reader.prototype.start = function() {
this.mainPromise = Promise.resolve()
.then(function() {
this.urandomStream = this.createReadStream('/dev/urandom');
this.urandomStream.setEncoding('hex');
this.urandomStream.on('data', this.onChunk);
});
// Returning it to keep the method could be tested.
return this.mainPromise;
};
Reader.prototype.onChunk = function(chunk) {
if (this.counter && this.counter === 5) {
this.urandomStream.close();
this.targetStream.close();
return;
}
this.createFile();
this.counter += 1;
this.mainPromise
.then(this.writeContent(chunk))
.catch(function(error) {
console.error(error);
});
};
Reader.prototype.createFile = function() {
if (0 === this.counter) {
this.filePath = this.paths[0];
} else if(2 === this.counter) {
this.filePath = this.paths[1];
}
this.targetStream = this.createWriteStream(this.filePath);
return Promise.resolve();
};
Reader.prototype.writeContent = function(chunk) {
return function() {
return new Promise(function(resolve, reject) {
this.targetStream.write(chunk, 'utf8', resolve);
});
};
};
var reader = new Reader();
reader.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment