-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfixJsonLD.js
54 lines (42 loc) · 1.53 KB
/
fixJsonLD.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
import fs from 'fs';
import path from 'path';
const fixJsonLD = (file)=>{
let htmlString = fs.readFileSync(file, 'utf-8');
// replacing p with script
htmlString = htmlString.replace(/<p.*?(type=?application\/ld\+json?)/, '<script $1');
const chunks = htmlString.split('application/ld+json');
chunks[1] = chunks[1].replace(/<\/p>/, '</script>');
htmlString = chunks.join('application/ld+json');
// extracting the json+ld
const jsonldscriptpattern = /<script type=?application\/ld\+json.*?<\/script>/;
let extractedJsonLD = htmlString.match(jsonldscriptpattern);
if(!extractedJsonLD){
process.exit(1);
}
// deleting the json+ld
htmlString = htmlString.replace(jsonldscriptpattern, '');
const chunks2 = htmlString.split('</head>');
chunks2[0] = chunks2[0] +''+ extractedJsonLD[0].replace(/"/g, '"');
htmlString = chunks2.join('</head>')
fs.writeFileSync(file, htmlString);
}
function listHtmlFiles(directoryPath) {
const htmlFiles = [];
function traverseDirectory(dir) {
const files = fs.readdirSync(dir);
files.forEach((file) => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
traverseDirectory(filePath);
} else if (path.extname(filePath) === '.html') {
htmlFiles.push(filePath);
}
});
}
traverseDirectory(directoryPath);
return htmlFiles;
}
listHtmlFiles('./dist').forEach((file)=>{
fixJsonLD(`./${file}`);
});