-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.js
102 lines (82 loc) · 2.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict';
const path = require('path');
const CpFileError = require('./cp-file-error');
const fs = require('./fs');
const ProgressEmitter = require('./progress-emitter');
module.exports = (src, dest, opts) => {
if (!src || !dest) {
return Promise.reject(new CpFileError('`src` and `dest` required'));
}
opts = Object.assign({overwrite: true}, opts);
const progressEmitter = new ProgressEmitter(path.resolve(src), path.resolve(dest));
const promise = fs
.stat(src)
.then(stat => {
progressEmitter.size = stat.size;
})
.then(() => fs.createReadStream(src))
.then(read => fs.mkdirp(path.dirname(dest)).then(() => read))
.then(read => new Promise((resolve, reject) => {
const write = fs.createWriteStream(dest, {flags: opts.overwrite ? 'w' : 'wx'});
read.on('data', () => {
progressEmitter.written = write.bytesWritten;
});
write.on('error', err => {
if (!opts.overwrite && err.code === 'EEXIST') {
resolve(false);
return;
}
reject(new CpFileError(`cannot write to \`${dest}\`: ${err.message}`, err));
});
write.on('close', () => {
progressEmitter.written = progressEmitter.size;
resolve(true);
});
read.pipe(write);
}))
.then(updateTimes => {
if (updateTimes) {
return fs.lstat(src).then(stats => fs.utimes(dest, stats.atime, stats.mtime));
}
});
promise.on = function () {
progressEmitter.on.apply(progressEmitter, arguments);
return promise;
};
return promise;
};
module.exports.sync = function (src, dest, opts) {
if (!src || !dest) {
throw new CpFileError('`src` and `dest` required');
}
opts = Object.assign({overwrite: true}, opts);
let read;
let bytesRead;
let pos;
let write;
const BUF_LENGTH = 100 * 1024;
const buf = new Buffer(BUF_LENGTH);
const readSync = pos => fs.readSync(read, buf, 0, BUF_LENGTH, pos, src);
const writeSync = () => fs.writeSync(write, buf, 0, bytesRead, undefined, dest);
read = fs.openSync(src, 'r');
pos = bytesRead = readSync(0);
fs.mkdirpSync(path.dirname(dest));
try {
write = fs.openSync(dest, opts.overwrite ? 'w' : 'wx');
} catch (err) {
if (!opts.overwrite && err.code === 'EEXIST') {
return;
}
throw err;
}
writeSync();
while (bytesRead === BUF_LENGTH) {
bytesRead = readSync(pos);
writeSync();
pos += bytesRead;
}
const stat = fs.fstatSync(read, src);
fs.futimesSync(write, stat.atime, stat.mtime, dest);
fs.closeSync(read);
fs.closeSync(write);
};