forked from applefreak/html-static-asset-path-extractor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extractor.js
42 lines (36 loc) · 1.03 KB
/
extractor.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
const fs = require('fs')
const path = require('path')
const htmlparser = require('htmlparser2').Parser
const mimeLookup = require('mime-types').contentType
const validStaticFile = require('./static-assets-ext').contains
const EXTRACT_DEFAULTS = {
link: 'href',
img: 'src',
script: 'src',
}
const getParser = (onopentag) => {
let parser = undefined
const initParser = () => {
parser = new htmlparser({ onopentag }, {decodeEntities: true})
return parser
}
return parser ? parser : initParser()
}
module.exports = (file, extracts = EXTRACT_DEFAULTS) => {
const result = []
// TODO handle error
const content = fs.readFileSync(file)
let parser = getParser((name, attrs) => {
if (name in extracts) {
const filePath = attrs[extracts[name]]
const ext = path.extname(filePath)
if (ext.length > 2 && validStaticFile(ext.substr(1))) {
const contentType = mimeLookup(filePath)
result.push({ filePath, contentType })
}
}
})
parser.write(content)
parser.end()
return result
}