编码转换获取响应 [英] Encoding conversion of a fetch response

查看:253
本文介绍了编码转换获取响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



只要抓取完成,我正在尝试转换它到UTF-8。



这里的代码:

  const iconv = require('iconv-lite'); 

fetch('http://www.band.uol.com.br/rss/colunista_64.xml',{
headers:{
Content-type: text / xml; charset = ISO-8859-1
}
})
.then(res => res.text()})
.then => {
const decodedText = iconv.decode(Buffer.from(text,'latin1'),'latin1')
,output = iconv.encode(decodedText,'utf8')
console.log(output.toString())
})

问题是:身体的所有特殊字符被¿½替换



对于转换,我使用的是 iconv-lite



这个问题的解决方法是什么?

解决方案>

最好的解决方法是使用 res.arrayBuffer()而不是 res.text()缓冲区构造函数接受 ArrayBuffer



代码:

 取('http://www.band.uol.com.br/rss/colun ista_64.xml')
.then(res => res.arrayBuffer())
.then(arrayBuffer => iconv.decode(new Buffer(arrayBuffer),'iso-8859-1')。toString())
.then(converted => ; console.log(转换))


Inside a React Native method I'm fetching a xml encoded in ISO-8859-1.

As long as the fetching is completed I'm trying to convert it to UTF-8.

Here the code:

const iconv = require('iconv-lite');

fetch('http://www.band.uol.com.br/rss/colunista_64.xml', {
      headers: {
        "Content-type": "text/xml; charset=ISO-8859-1"
      }
})
.then(res=>res.text()})
.then(text => {
   const decodedText = iconv.decode(Buffer.from(text, 'latin1'), 'latin1')
  , output = iconv.encode(decodedText, 'utf8')
   console.log(output.toString())
})

The problem is: all especial characters of the body is being replaced by "¿½"

For the conversion, I'm using the package iconv-lite

What is the better workaround for this problem?

解决方案

The best workaround is to use res.arrayBuffer() instead res.text(), as long the Buffer constructor accepts ArrayBuffer

The code:

fetch('http://www.band.uol.com.br/rss/colunista_64.xml')
      .then(res => res.arrayBuffer())
      .then(arrayBuffer => iconv.decode(new Buffer(arrayBuffer), 'iso-8859-1').toString())
      .then(converted => console.log(converted))

这篇关于编码转换获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆