-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (85 loc) · 2.33 KB
/
index.js
File metadata and controls
92 lines (85 loc) · 2.33 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
88
89
90
91
92
const fs = require("fs");
module.exports = function FileWriter() {
this.queue = [];
this.error = false;
this.completed = [];
this.add = (path, filename, data = null) => {
this.queue.push({ path, filename, data });
};
this.remove = (path) => {
this.queue = this.queue.filter((file) => file.path !== path);
};
this.createDir = (path) => {
if (!fs.existsSync(path)) {
fs.mkdirSync(path, { recursive: true, force: true });
}
};
this.process = (dry = false) => {
// Check for dir and create if not exists.
if (fs.existsSync(`.tmp`)) {
fs.rmSync(`.tmp`, { recursive: true, force: true });
}
// Create temporary files.
this.queue.forEach((file) => {
if (this.error) {
return;
}
try {
this.createDir(`.tmp/${file.path}`, {
recursive: true,
force: true,
});
// Create file.
file.data &&
fs.writeFileSync(`.tmp/${file.path}/${file.filename}`, file.data, {
recursive: true,
force: true,
});
} catch (err) {
this.error = err;
return;
}
});
// Delete the temporary files if an error occurred.
if (this.error) {
fs.rmSync(".tmp", { recursive: true, force: true });
return this.error;
}
// Stop here if dry run.
if (dry) return this.error;
// Move the temporary files to the correct location once they have been verified for accuracy.
this.queue.forEach((file, i) => {
if (this.error) {
this.completed.forEach((file) => {
fs.rmSync(`${file.path}/${file.filename}`, {
recursive: true,
force: true,
});
});
return this.error;
}
try {
// Check for dir and create if not exists.
if (!fs.existsSync(file.path)) {
this.createDir(file.path, {
recursive: true,
force: true,
});
}
fs.renameSync(
`.tmp/${file.path}/${file.filename}`,
`./${file.path}/${file.filename}`
);
delete this.queue[i];
this.completed.push(file);
} catch (err) {
this.error = err;
return;
}
});
// Delete the temp dir.
fs.rmSync(".tmp", { recursive: true, force: true });
return this.error;
};
return this;
};