Debian Codegraph @

lib/dest/write-contents/write-stream.js

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