This code attempts to replace image URLs with a Base 64 data string.
I can't get the src attributes to update to base64String
. It's unclear if the problem stems from the axios promise, or setAttribute.
const dom = new JSDOM(body, { includeNodeLocations: true, QuerySelector: true, FetchExternalResources: true })
const document = dom.window.document
const imageElements = document.querySelectorAll('img')
imageElements.forEach(async imageElement => {
const src = imageElement.getAttribute('src')
axios
.get(src, { responseType: 'arraybuffer' })
.then(image => {
const raw = Buffer.from(image.data).toString('base64')
const base64String = 'data:' + image.headers['content-type'] + ';base64,' + raw
imageElement.setAttribute('src', base64String)
})
.catch(error => {
rejects(error)
})
})
const article = new Readability(document).parse()
const content = sanitizeHtml(article.content, {
allowedTags: ['h1', 'p' 'a', 'img'],
allowedAttributes: { img: ['src'] },
})
console.log(content)
// Expect images to be replaced with data string. Original image urls remain as src attributed.