Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. const stream = require('stream');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const mkdirp = require('mkdirp');
  5.  
  6. class ToFileStream extends stream.Writable {
  7. constructor() {
  8. super({ objectMode: true }); // [1]
  9. }
  10.  
  11. _write(chunk, encoding, callback) { // [2]
  12. mkdirp(path.dirname(chunk.path), (err) => {
  13. if(err) {
  14. callback(err);
  15. }
  16. fs.writeFile(chunk.path, chunk.content, callback);
  17. })
  18. }
  19. }
  20.  
  21. const tfs = new ToFileStream();
  22.  
  23. tfs.write({
  24. path: './fileCreatorFiles/file1.txt',
  25. content: 'Hello'
  26. });
  27.  
  28. tfs.write({
  29. path: './fileCreatorFiles/file2.txt',
  30. content: 'Nodejs'
  31. });
  32.  
  33. tfs.write({
  34. path: './fileCreatorFiles/file3.txt',
  35. content: 'Streams!'
  36. });
  37.  
  38. tfs.end(() => {
  39. console.log('All files created');
  40. })
  41.  
  42. // [1] `objectMode` true to allow writable stream to accept object data type.
  43. // Other acceptable arguments:
  44. // - `highWaterMark`: controls internal buffer limit
  45. // - `decodeStrings`: enables automatic decoding of strings into binary
  46. // buffers before passing to _write() method. Defaults to true
  47. //
  48. // [2] the _write() implementation accepts a callback which is invoked when
  49. // the operation completes. It is not necessary to pass the result to
  50. // callback; but we can pass an error which will cause the stream to
  51. // emit an `error` event.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement