Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement