JSDOM:使用 base64 字符串更新“src”属性

问题描述

代码尝试用 Base 64 数据字符串替换图像 URL。

我无法将 src 属性更新为 base64String。目前尚不清楚问题是否源于 axios 承诺或 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.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)