2

I have a file with name test.txt following data "qwe abc xyz"

And my code is as follows:

let data = fs.readFileSync('test.txt', 'utf8')
    console.log(data)
    data = data.substring(2) //doing this because first two chars are garbage
    console.log(data)
    let data2 = data.replace('abc', 'Decimal');
    console.log(data2)

Output of this code:

��qwe abc xyz
qwe abc xyz
qwe abc xyz

Why isn't my abc getting replaced with Decimal in data2? I have tried with following as well:

let data = fs.readFileSync('test.txt', 'utf8')
    console.log(data)
    data = data.substring(2) //doing this because first two chars are garbage
    console.log(data)
    let data2 = data.replace(/abc/g, 'Decimal');
    console.log(data2)

Still it gives the same output. What could be the issue? Can it be related to sync/async?

rishiag
  • 2,248
  • 9
  • 32
  • 57

1 Answers1

-1

Edit:
As per comments, the file in question was utf-16 little endian. The answer provided here worked.

let data = fs.readFileSync('test.txt', 'utf16le');

Original answer
See answer here. You have to convert the string to utf8.

let data = fs.readFileSync('test.txt', 'utf8');
data = data.toString('utf8').replace(/^\uFEFF/, '');
Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32
  • This didn't work. I think that answer is related to reading the file with correct encoding whereas my issue is replace command not working. I also checked the encoding of text.txt file and it is file -I test.txt test.txt: text/plain; charset=utf-16le – rishiag Jun 04 '20 at 07:07
  • you should try logging the string length. It might give you a clue. There are cases where invisible characters are inserted in between all or some characters. – Rahul Bhobe Jun 04 '20 at 07:16
  • Also see the answer: https://stackoverflow.com/a/14404102/11057988 – Rahul Bhobe Jun 04 '20 at 07:19