/
copy-file-sync.js
68 lines (60 loc) 路 2.09 KB
/
copy-file-sync.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
/**
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const path = require("path")
const fs = require("fs-extra")
//------------------------------------------------------------------------------
// Exports
//------------------------------------------------------------------------------
/**
* Copy a file synchronously.
* Additionally, copy file attributes also by options.
* @param {string} source - A path of the source file.
* @param {string} output - A path of the destination file.
* @param {object} options - Options.
* @param {boolean} options.preserve - The flag to copy attributes.
* @param {boolean} options.update - The flag to disallow overwriting.
* @returns {void}
* @private
*/
module.exports = function copyFileSync(source, output, options) {
const stat = fs.statSync(source)
if (options.update) {
try {
const dstStat = fs.statSync(output)
if (dstStat.mtime.getTime() > stat.mtime.getTime()) {
// Don't overwrite because the file on destination is newer than
// the source file.
return
}
} catch (_err) {
// ignore - The file may not exist.
}
}
if (stat.isDirectory()) {
fs.ensureDirSync(output)
} else {
fs.ensureDirSync(path.dirname(output))
if (!(stat.mode & 0o200) && options.force) {
try {
fs.chmodSync(output, stat.mode | 0o200)
} catch (dstChmodError) {
if (dstChmodError.code !== "ENOENT") {
throw dstChmodError
}
}
}
fs.copySync(source, output)
}
fs.chmodSync(output, stat.mode)
if (options.preserve) {
fs.chownSync(output, stat.uid, stat.gid)
fs.utimesSync(output, stat.atime, stat.mtime)
}
}