forked from regisphilibert/hugoGetApi
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cli.js
38 lines (33 loc) · 1.21 KB
/
cli.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
'use strict';
const {readdirSync, statSync, readFileSync, writeFileSync} = require('fs');
const {join} = require('path');
function getAllFiles(dirPath, ext) {
function flatten(arr) {
return arr.reduce((flat, toFlatten) => flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten), []);
}
function scanDir(dirPath, ext) {
const result = readdirSync(dirPath);
if (!result.length) return [];
return result.map((dirName) => {
const filePath = join(dirPath, dirName);
if (statSync(filePath).isDirectory()) {
return scanDir(join(dirPath, dirName), ext);
} else {
if (!ext) return filePath;
if (filePath.lastIndexOf(ext) === filePath.indexOf(ext) && filePath.indexOf(ext) > -1) return filePath;
return '';
}
});
}
return flatten(scanDir(dirPath, ext)).filter((file) => file);
}
const allMarkdownFiles = getAllFiles('./public', '.json');
allMarkdownFiles.forEach((item) => {
try {
const jsonData = JSON.stringify(JSON.parse(readFileSync(item, 'utf8')));
writeFileSync(item, jsonData);
} catch (e) {
console.error(`${item} content error.`);
// writeFileSync(item, JSON.stringify({code: 500, desc: 'Unexpected token'}));
}
});