Skip to content

Instantly share code, notes, and snippets.

@artze
Created June 9, 2019 08:52
Show Gist options
  • Save artze/5da6fee904d21c2fe01a29ccc63e1e42 to your computer and use it in GitHub Desktop.
Save artze/5da6fee904d21c2fe01a29ccc63e1e42 to your computer and use it in GitHub Desktop.
Create a custom writable stream that creates text files
const stream = require('stream');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
class ToFileStream extends stream.Writable {
constructor() {
super({ objectMode: true }); // [1]
}
_write(chunk, encoding, callback) { // [2]
mkdirp(path.dirname(chunk.path), (err) => {
if(err) {
callback(err);
}
fs.writeFile(chunk.path, chunk.content, callback);
})
}
}
const tfs = new ToFileStream();
tfs.write({
path: './fileCreatorFiles/file1.txt',
content: 'Hello'
});
tfs.write({
path: './fileCreatorFiles/file2.txt',
content: 'Nodejs'
});
tfs.write({
path: './fileCreatorFiles/file3.txt',
content: 'Streams!'
});
tfs.end(() => {
console.log('All files created');
})
// [1] `objectMode` true to allow writable stream to accept object data type.
// Other acceptable arguments:
// - `highWaterMark`: controls internal buffer limit
// - `decodeStrings`: enables automatic decoding of strings into binary
// buffers before passing to _write() method. Defaults to true
//
// [2] the _write() implementation accepts a callback which is invoked when
// the operation completes. It is not necessary to pass the result to
// callback; but we can pass an error which will cause the stream to
// emit an `error` event.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment