简体   繁体   English

使用Windows 1252在node.js中编码字符串

[英]Encode a string using windows 1252 in node.js

I want to encode a string in Node.js using windows-1252 encoding scheme. 我想使用Windows-1252编码方案在Node.js中编码字符串。 How can I do that ? 我怎样才能做到这一点 ?

I just had the same problem when retrieving data from old websites with ANSI (windows-1252) encoding. 使用ANSI(windows-1252)编码从旧网站检索数据时,我遇到了同样的问题。 Some characters come out messed up. 一些字符出来搞砸了。 like: 像:

Here is how I solved. 这是我解决的方法。 Based on the API doc : 根据API doc

var req = http.request(options, (res) => {
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

Just change res.setEncoding('utf8'); 只需更改res.setEncoding('utf8'); into res.setEncoding('binary'); 进入res.setEncoding('binary'); . It seems to accept both utf8 and ansi encoding without messing the accents. 它似乎接受utf8ansi编码,而不会弄乱口音。

res.setEncoding('binary');

You can use any of these packages. 您可以使用这些软件包中的任何一个。 Just go through the guide. 只是通过指南。 First one is exactly meant for what you need. 第一个恰好满足您的需求。 The other one takes care of many more legacy encoding. 另一个负责更多的传统编码。

https://github.com/mathiasbynens/windows-1252 https://github.com/mathiasbynens/windows-1252

https://www.npmjs.com/package/legacy-encoding https://www.npmjs.com/package/legacy-encoding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM