13

I need to convert a string from Windows-1251 to UTF-8.

I tried to do this with iconv, but all I get is something like this:

пїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ

var iconv = new Iconv('windows-1251', 'utf-8')
title = iconv.convert(title).toString('utf-8')
Pang
  • 9,564
  • 146
  • 81
  • 122
user1125115
  • 131
  • 1
  • 1
  • 3
  • possible duplicate of [nodejs http response encoding](http://stackoverflow.com/questions/5135450/nodejs-http-response-encoding) – Octavian Helm Jan 29 '12 at 00:47

3 Answers3

25

Here is working solution to your problem. You have to use Buffer and convert your string to binary first.

const Iconv = require('iconv').Iconv;

request({ 
    uri: website_url,
    method: 'GET',
    encoding: 'binary'
}, function (error, response, body) {

        const body = new Buffer(body, 'binary');
        conv = Iconv('windows-1251', 'utf8');
        body = conv.convert(body).toString();

});
Ahmet Şimşek
  • 1,391
  • 1
  • 14
  • 24
Alex Kolarski
  • 3,255
  • 1
  • 25
  • 35
  • +1 Your solution worked for me. Thanks. But instead of `iconv` I used the [windows1251](https://www.npmjs.com/package/windows-1251) – Azevedo Apr 11 '17 at 22:52
0

If you're reading from file, you could use something like that:

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

fs.readFile("filename.xml", null, (err, data) => { 
    if(err) { 
        console.log(err)
        return
    }

    const encodedData = iconv.encode(iconv.decode(data, 'win1251'), 'utf8')
    fs.writeFile("result_filename.xml", encodedData, () => { })
})
Konstantin Nikolskii
  • 1,075
  • 1
  • 12
  • 17
0

I use Node version 16 and code bellow works fine. You don't need to use Buffer node will write warnings. You need to install iconv package before.

        fs = require('fs')
        fs.readFile('printed_document.txt', function (err,data) {
            if (err) {
                return console.log(err);
            }
            console.log(require('iconv').Iconv('windows-1251', 'utf-8').convert(data).toString())
        })
Orlov Const
  • 332
  • 3
  • 10