iconv.decode()导致的问题以及解决方法
2016-11-23 19:09
344 查看
https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding
在使用iconv.decode()解码之前,最初的资源已经通过
如果你设置了res.setEncoding(‘utf8’);。那么和上面的转化是一样的。
对于最开始的问题,使用了两次解码(无论一次还是两次),都是错误的结果。几乎是不可能地回复最初的字节因为utf8转换是有损耗的(lossy)。所以即使是
注意: theoretically, if you use ‘binary’ encoding to first decode to strings, then feed them to decode, you get the correct results. This is a bad practice because it’s slower, it’s mixing concepts and ‘binary’ encoding is deprecated.
这段不是很懂什么意思,反正使用’binary’编码是不赞成的。(二进制编码?)
首先需要知道的是,在data事件的时候,所有的js字符串都是经过解码(utf8)的,我们就不需要手动解码了。
如果想要忽略警告:
问题
var http = require('http'), iconv = require('iconv-lite'); http.get("http://website.com/", function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { var decodedBody = iconv.decode(body, 'win1252'); // 或者gbk/gb2312等 console.log(decodedBody); }); });
在使用iconv.decode()解码之前,最初的资源已经通过
body += chunk解码了,发生了什么:
res.on('data', function(chunkBuffer) { body += chunkBuffer.toString('utf8'); });
如果你设置了res.setEncoding(‘utf8’);。那么和上面的转化是一样的。
对于最开始的问题,使用了两次解码(无论一次还是两次),都是错误的结果。几乎是不可能地回复最初的字节因为utf8转换是有损耗的(lossy)。所以即使是
iconv.decode(new Buffer(body, 'utf8'), 'win1252')也无济于事。
注意: theoretically, if you use ‘binary’ encoding to first decode to strings, then feed them to decode, you get the correct results. This is a bad practice because it’s slower, it’s mixing concepts and ‘binary’ encoding is deprecated.
这段不是很懂什么意思,反正使用’binary’编码是不赞成的。(二进制编码?)
解决方案
保持开始的buffer并且使用
iconv.decode,如果有必要,可以使用
Buffer.concat()。
首先需要知道的是,在data事件的时候,所有的js字符串都是经过解码(utf8)的,我们就不需要手动解码了。
http.get("http://website.com/", function(res) { var chunks = []; res.on('data', function(chunk) { chunks.push(chunk); }); res.on('end', function() { var decodedBody = iconv.decode(Buffer.concat(chunks), 'win1252'); console.log(decodedBody); }); }); // Or, with iconv-lite@0.4 and Node v0.10+, you can use streaming support with `collect` helper http.get("http://website.com/", function(res) { res.pipe(iconv.decodeStream('win1252')).collect(function(err, decodedBody) { console.log(decodedBody); }); });
如果想要忽略警告:
iconv.skipDecodeWarning = true;
相关文章推荐
- 【简译】JavaScript闭包导致的闭合变量问题以及解决方法
- Centos6.5(final)安装gcc和g++,python以及导致问题的解决方法
- 计算机小技巧集锦 (增加你计算机的安全系数以及一些问题的解决方法)
- 使用java mail 包收发中文邮件的编码,解码问题以及解决方法
- LoadRunner本机录制http协议程序遇到的问题以及解决方法
- 关于hibernate和jsp,以及中文编码问题的传统解决方法
- 由于计算机磁盘硬件配置出现问题,导致 Windows 无法启动的解决方法 由于计算机磁盘硬件配置出现问题,导致 Windows 无法启动
- 在Ubuntu下安装VMware Tools导致鼠标滚轮不能用的问题的解决方法
- domino中java代理导致内存溢出问题的解决方法
- 整理ArcSDE 安装过程出现问题以及解决方法系列
- Vista的一些问题以及相应的解决方法
- 浅谈ajax中get与post的区别,以及ajax中的乱码问题的解决方法
- 今天遇到的几个问题以及解决方法
- 整理ArcSDE 安装过程出现问题以及解决方法系列
- 关于 clock_gettime() 的一个问题以及解决方法
- 关于流和缓冲区的理解以及一般标准输入问题的解决方法小结.
- 卸载IE7可能产生的几个问题以及解决方法
- 基于消息分发的多线程程序设计,常见的问题,以及解决方法
- 某些导致不能安装SQL SERVER 2005的问题及解决方法
- 把同一个Resource添加到同一个Group中两个不同Application导致的问题及解决方法