forked from Sensing-Dev/doc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostprocess.js
42 lines (32 loc) · 1.43 KB
/
postprocess.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
// postprocess.js
'use strict';
const fs = require('fs-extra');
const path = require('path');
const recursiveReaddir = require('recursive-readdir');
const buildDirectory = path.join(__dirname, 'build');
const absoluteUrlRegExp = /(href|src)="(?!http[s]|ftp?:\/\/)([^"|#]+)"/g;
const isDirectory = dirPath => path.extname(dirPath) === '';
const convertAbsolutePathsToRelative = (content, filePath) =>
content.replace(absoluteUrlRegExp, (_absoluteUrl, $1, $2) => {
const currentDirPath = path.dirname(filePath);
const relativeDirPath = currentDirPath === '.' ? '.' : path.relative(currentDirPath, '');
let relativePath = path.join(relativeDirPath, $2);
if (isDirectory(relativePath)) {
relativePath = path.join(relativePath, 'index.html');
}
return `${$1}="${relativePath}"`;
});
const websiteTextualFileExtensions = ['.css', '.js', '.html', '.xml'];
const isNotWebsiteTextualFile = (filePath, stats) =>
!(stats.isDirectory() || websiteTextualFileExtensions.includes(path.extname(filePath)));
const postProcess = async () => {
const filePaths = await recursiveReaddir(buildDirectory, [isNotWebsiteTextualFile]);
await Promise.all(
filePaths.map(async filePath => {
const content = await fs.readFile(filePath);
const relativePath = path.relative(buildDirectory, filePath);
await fs.writeFile(filePath, convertAbsolutePathsToRelative(String(content), relativePath));
})
);
};
postProcess();