forked from w3c/webref
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
75 lines (66 loc) · 1.84 KB
/
utils.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
/**
* Common functions for use in tools
*/
const fs = require('fs').promises;
const path = require('path');
async function createFolderIfNeeded(folder) {
try {
await fs.mkdir(folder);
}
catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
}
};
/**
* Load a JSON file as JS object.
*
* @function
* @param {String} filename The path to the file to require
* @return {Object} The result of loading and parsing the file relative to the
* current working directory.
*/
async function loadJSON(filename) {
try {
const json = await fs.readFile(filename, 'utf8');
return JSON.parse(json);
}
catch (err) {
return null;
}
};
/**
* Copy the contents of the given folder to the target folder recursively.
*
* @function
* @param {String} source The folder to copy
* @param {String} target The folder that should contain the copy. The folder
* gets created if it does not exist.
* @param {Object} options Copy options. Set "excludeRoot" to exclude the root
* folder from the copy and start the copy with its contents
* @return {Promise} The promise to have copied the folder's contents.
*/
async function copyFolder(source, target, { excludeRoot = false } = {}) {
// Check if folder needs to be created or integrated
const targetFolder = excludeRoot ?
target :
path.join(target, path.basename(source));
await createFolderIfNeeded(targetFolder);
const folderContent = await fs.readdir(source);
return Promise.all(folderContent.map(async name => {
const fileOrFolder = path.join(source, name);
const stat = await fs.lstat(fileOrFolder);
if (stat.isDirectory()) {
return copyFolder(fileOrFolder, targetFolder);
}
else {
return fs.copyFile(fileOrFolder, path.join(targetFolder, name));
}
}));
};
module.exports = {
createFolderIfNeeded,
loadJSON,
copyFolder
};