After reading file using fs.readFileSync(), string replace function is not working

Viewed 975

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?

1 Answers

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/, '');
Related