-
Notifications
You must be signed in to change notification settings - Fork 0
/
html_editor.js
87 lines (76 loc) · 2.95 KB
/
html_editor.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
76
77
78
79
80
81
82
83
84
85
86
87
/**
* @description Class that is responsible for editing HTML files.
* Contains methods to retrieve JS files or code.
*
* @version 0.1
* @author Kishan Nirghin
* @Date 12-02-2019
*/
const cheerio = require("cheerio"),
fs = require("fs"),
path = require("path");
VALID_JS_TYPES = ['text/javascript', 'application/javascript', 'application/ecmascript', 'text/ecmascript'];
module.exports = class HTMLEditor {
loadFile(filePath) {
this.filePath = filePath;
this.source = this.originalSource = fs.readFileSync(filePath).toString();
this.html = this.originalHtml = cheerio.load(this.source);
return this;
}
getExternalScripts() {
var cScripts = this.html('script');
var scripts = [];
cScripts.each((index, cScriptElement) => {
if (cScriptElement.attribs["src"]) {
var scriptType = cScriptElement.attribs["type"];
if (scriptType && !VALID_JS_TYPES.includes(scriptType)) return;
var relativeScriptSrc = cScriptElement.attribs["src"];
if (relativeScriptSrc.toLowerCase().startsWith("http:/") || relativeScriptSrc.toLowerCase().startsWith("https:/")) { return;}
var scriptSrc = path.join(
path.dirname(this.filePath),
relativeScriptSrc
);
scripts.push({
src: scriptSrc,
index: index
});
}
});
return scripts;
}
getInternalScripts() {
var cScripts = this.html('script');
var scripts = [];
cScripts.each((index, cScriptElement) => {
if (!cScriptElement.attribs["src"]) {
var scriptType = cScriptElement.attribs["type"];
if (scriptType && !VALID_JS_TYPES.includes(scriptType)) return;
var source = cheerio(cScriptElement).html();
var bodyStart = this.source.indexOf(source);
var bodyEnd = bodyStart + source.length;
scripts.push({
src: this.filePath,
index: index,
source: cheerio(cScriptElement).html(),
bodyRange: [bodyStart, bodyEnd]
});
}
});
return scripts;
}
/**
* Update an inline script in the html
* @param {*} script the original script content
* @param {*} newScript the new script content
*/
updateInternalScript(oldScriptContent, newScriptContent) {
var index = this.source.indexOf(oldScriptContent);
if (index < 0) {
return console.log("html_editor updateInternalScript error: oldScriptContent not found");
}
this.source = this.source.splice(index, oldScriptContent.length, newScriptContent);
}
saveFile() {
fs.writeFileSync( this.filePath, this.source );
}
}