-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrite.js
93 lines (85 loc) · 2.01 KB
/
write.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
const fs = require('fs');
const fsWrite = (url = '', callback) => {
if (!url) return;
const pathList = url.split('\\');
let index = fileExistsNum(pathList);
function write() {
index++;
// if (index > 0) return;
if (index >= 0) {
const filePath = pathList.join('\\');
callback && callback(filePath);
} else {
const filePath = pathList.slice(0, index).join('\\');
fs.mkdirSync(filePath);
write();
}
}
write();
};
const fileExistsNum = (pathList = []) => {
let index = 0;
function fn() {
let filePath = '';
if (index === 0) {
filePath = pathList.join('\\');
} else {
filePath = pathList.slice(0, index).join('\\');
}
const flag = fs.existsSync(filePath);
if (flag) return index;
index--;
return fn();
}
return fn();
};
const fileWrite = (url = '', content = '', cb) => {
const callback = (filePath) => {
fs.writeFile(filePath, content, (err) => {
if (err) {
cb && cb(err);
return;
}
cb && cb();
});
};
try {
fsWrite(url, callback);
} catch (e) {
cb && cb(e);
}
};
const fileWriteSync = (url = '', content = '') => {
const callback = (filePath) => {
fs.writeFileSync(filePath, content);
};
fsWrite(url, callback);
};
const dirWrite = (url = '') => {
const callback = (filePath) => {
fs.mkdirSync(filePath);
};
fsWrite(url, callback);
};
const dirWriteSync = (url = '', cb) => {
const callback = (filePath) => {
fs.mkdir(filePath, (err) => {
if (err) {
cb && cb(err);
return;
}
cb && cb();
});
};
try {
fsWrite(url, callback);
} catch (e) {
cb && cb(e);
}
};
module.exports = {
fileWrite,
fileWriteSync,
dirWrite,
dirWriteSync
};