C
C
CodeVision2022-03-13 22:15:00
Node.js
CodeVision, 2022-03-13 22:15:00

Text encoding error?

The code

const request = require('request'),
      fs = require('fs'),
      download = require('download');

request('https://litportal.ru/trial/txt/6376244.txt',async (err,res,body)=>{
        //res.headers['set-cookie']= 'xf_csrf=eHdNmSDvH01MoWk8; path=/; secure';
let file = fs.writeFileSync('./test.txt',JSON.stringify(res.body).toString(),'utf-8');
console.log(file);
})


Result:
622e42a65277a712162934.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
black1277, 2022-03-14
@black1277

The request library has been deprecated for a long time. It's better to use axios instead.
You are trying to read a remote file in ANSI encoding and re-encode to UTF-8.
You will need the iconv-lite library for this . Install it:
npm i iconv-lite
Then you can use this code:

const request = require('request'),
  fs = require('fs'),
  iconv = require('iconv-lite');

request({
  url: 'https://litportal.ru/trial/txt/6376244.txt',
  encoding: null,
  body: 'Buffer'
}).pipe(iconv.decodeStream('win1251'))
  .pipe(iconv.encodeStream('utf8'))
  .pipe(fs.createWriteStream('file-in-utf8.txt'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question