guyjasper
guyjasper

Reputation: 11

NodeJS Buffer.toString("ascii"), unable to search string

I'm using NodeJS and the "n-readlines" package to read a txt file line by line. I then convert the read line to "ascii" and assign to a variable. But when I try to search a string from the readline, it doesn't seem to work even if the search string is present.

const nReadlines = require("n-readlines");

let line;

const lines = new nReadlines(File);
while ((line = lines.next())) {
    let nLine = line.toString('ascii');
    if (nLine.indexOf("SearchString") >= 0) {
        //do something here
    }
}

I suspect this has to do with the encoding? when I try to get substring with 4 as length, the returned string is just 2 characters.

What could be wrong here? Thanks.

Got the sample code above to readlines from this link: ReadLines

EDIT: Okay, I think I know where the problem is. The line read from the file is represented as multi-byte characters. Changing the code

line.toString('ascii')

To

line.toString('utf16le')

seems to solve my problem.

Upvotes: 0

Views: 408

Answers (1)

guyjasper
guyjasper

Reputation: 11

Okay, I think I know where the problem is. The line read from the file is represented as multi-byte characters. Changing the code

line.toString('ascii')

To

line.toString('utf16le')

seems to solve my problem.

Upvotes: 1

Related Questions