write-stream.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. var fo = require('../../file-operations');
  3. var readStream = require('../../src/read-contents/read-stream');
  4. function writeStream(file, optResolver, onWritten) {
  5. var flags = fo.getFlags({
  6. overwrite: optResolver.resolve('overwrite', file),
  7. append: optResolver.resolve('append', file),
  8. });
  9. var opt = {
  10. mode: file.stat.mode,
  11. // TODO: need to test this
  12. flags: flags,
  13. };
  14. // TODO: is this the best API?
  15. var outStream = fo.createWriteStream(file.path, opt, onFlush);
  16. file.contents.once('error', onComplete);
  17. outStream.once('error', onComplete);
  18. outStream.once('finish', onComplete);
  19. // TODO: should this use a clone?
  20. file.contents.pipe(outStream);
  21. function onComplete(streamErr) {
  22. // Cleanup event handlers before closing
  23. file.contents.removeListener('error', onComplete);
  24. outStream.removeListener('error', onComplete);
  25. outStream.removeListener('finish', onComplete);
  26. // Need to guarantee the fd is closed before forwarding the error
  27. outStream.once('close', onClose);
  28. outStream.end();
  29. function onClose(closeErr) {
  30. onWritten(streamErr || closeErr);
  31. }
  32. }
  33. // Cleanup
  34. function onFlush(fd, callback) {
  35. // TODO: removing this before readStream because it replaces the stream
  36. file.contents.removeListener('error', onComplete);
  37. // TODO: this is doing sync stuff & the callback seems unnecessary
  38. // TODO: Replace the contents stream or use a clone?
  39. readStream(file, complete);
  40. function complete() {
  41. if (typeof fd !== 'number') {
  42. return callback();
  43. }
  44. fo.updateMetadata(fd, file, callback);
  45. }
  46. }
  47. }
  48. module.exports = writeStream;