-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
47 lines (41 loc) · 1.35 KB
/
Copy pathindex.js
File metadata and controls
47 lines (41 loc) · 1.35 KB
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
const fetch = require('isomorphic-unfetch');
const parse5 = require('parse5');
const imageWrapperIds = [
'img-canvas',
'imgTagWrapperId',
'digitalMusicProductImage_feature_div',
]
const searchTree = (node, targetIds) => {
const targetWrapper = node.childNodes && node.childNodes.find(_node => _node.attrs && _node.attrs.some(attr => attr.name === 'id' && targetIds.indexOf(attr.value) >= 0));
if (targetWrapper) {
return targetWrapper;
} else if (node.childNodes != null) {
let i;
let result = null;
for (let i = 0; result == null && i < node.childNodes.length; i += 1){
result = searchTree(node.childNodes[i], targetIds);
}
return result;
}
return null;
}
const amazonMetadataParser = (url) => {
return new Promise((resolve, reject) => {
fetch(url, {
headers: {
'Content-type': 'text/html',
}
})
.then(response => response.text())
.then((html) => {
const document = parse5.parse(html);
const imageWrapper = searchTree(document, imageWrapperIds);
const image = imageWrapper.childNodes.find(node => node.tagName === 'img');
resolve({
title: image.attrs.find(attr => attr.name === 'alt').value,
image: image.attrs.find(attr => attr.name === 'src').value
});
}).catch(reject);
});
}
module.exports = amazonMetadataParser;