forked from lgwebdream/fe-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.js
More file actions
87 lines (76 loc) · 1.95 KB
/
file.js
File metadata and controls
87 lines (76 loc) · 1.95 KB
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
const { join } = require('path');
const {
readdirSync,
readFile,
writeFile,
createReadStream,
createWriteStream,
existsSync,
mkdirSync,
} = require('fs');
const handleError = err => err && console.error(err) && process.exit(-1);
/**
* 迁移文件到固定目录
*
* @param {*} fromPath 需要迁移的文件夹路径
* @param {*} toPath 目的文件夹路径
* @param {*} ignoreFiles 需要忽略的文件名集合
* @returns
*/
const transferDir = (fromPath, toPath, ignoreFiles = []) => {
if (!existsSync(fromPath)) return;
// not exist and mkdir
!existsSync(toPath) && mkdirSync(toPath);
const files = readdirSync(fromPath, { withFileTypes: true });
for (const file of files) {
if (!ignoreFiles.includes(file.name)) {
const fromFilePath = join(fromPath, file.name);
const toFilePath = join(toPath, file.name);
if (file.isFile()) {
// copy file
const reader = createReadStream(fromFilePath);
const writer = createWriteStream(toFilePath);
reader.pipe(writer);
} else {
transferDir(fromFilePath, toFilePath);
}
}
}
};
/**
* 重写文件内容
*
* @param {*} fromFile
* @param {*} toFile
* @param {*} formatter 格式化回调 data => string
*/
const transferFile = (fromFile, toFile, formatter = null) => {
return new Promise((resolve, reject) => {
if (!existsSync(fromFile)) {
reject(`${fromFile} not exist`);
return;
}
readFile(fromFile, 'utf8', (err, data) => {
if (err) {
handleError(err);
reject(err);
return;
}
// formatter for data
const replaceData =
formatter && typeof formatter === 'function' ? formatter(data) : data;
writeFile(toFile, replaceData, 'utf8', err => {
if (err) {
handleError(err);
reject(err);
return;
}
resolve(true);
});
});
});
};
module.exports = {
transferDir,
transferFile,
};