Home > Net >  Why utf8 encode not working with filesync?
Why utf8 encode not working with filesync?

Time:11-21

I have data in file. When I want to read-out, the console does not encode it. When I just copy a part of it into my code and print it then it works normally.

Expected outcome:

var data =`
"PaymentMode": "CARDPAYMENT",
"GrossDeliveryPrice": "1999.00",
"GrossCODFee": "0.00",
"CourierName": "fut\u00e1rszolg\u00e1lata",
"BillingAddress": {
    "City": "P\u00fcsp\u00f6klad\u00e1ny",
    "Street": "Kolozsv\u00e1ri, 19\/1",`


console.log(data);

----------------

"PaymentMode": "CARDPAYMENT",
"GrossDeliveryPrice": "1999.00",
"GrossCODFee": "0.00",
"CourierName": "futárszolgálata",
"BillingAddress": {
    "City": "Püspökladány",
    "Street": "Kolozsvári, 19/1",

But instead I got a following result when read out the file.

const fs = require('fs');
  
const data = fs.readFileSync(__dirname   "/logs/file.txt",
            {encoding:'utf8', flag:'r'});
 
console.log(data);

------------------------

"PaymentMode": "CARDPAYMENT",
"GrossDeliveryPrice": "1999.00",
"GrossCODFee": "0.00",
"CourierName": "fut\u00e1rszolg\u00e1lata",
"BillingAddress": {
    "City": "P\u00fcsp\u00f6klad\u00e1ny",
    "Street": "Kolozsv\u00e1ri, 19\/1",

Why it is not converted into the right format?

CodePudding user response:

Use

const fs = require('fs');
const file = fs.readFileSync(__dirname   '/logs/file.txt', {encoding:'utf8', flag:'r'});

const result = file.replace(/\\u([\d\w]{4})/gi, function (match, grp) {
        return String.fromCharCode(parseInt(grp, 16));
});

console.log(result);

As this

const result = file.replace(/\\u([\d\w]{4})/gi, function (match, grp) {
        return String.fromCharCode(parseInt(grp, 16));
});

Replaces/changes words after \ to special words.

  • Related