Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

xml - Encoding conversion of a fetch response

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...