Fabio Ricci
Fabio Ricci

Reputation: 387

How to convert ISO-8859-1 to UTF-8 in node.js from readfile buffer

as per title, I am trying to parse a txt encoded in ISO-8859-1 to put data into a DB. I do need that these data is converted into UTF-8 before. This is due to the fact that some special character, particularly uppercase accented characters, are shown as question mark in the DB and in front-end consequently.

The code I am using is:

this.fs.readFile(fileName, null, function(err, buff){
                    if (err) {
                        self.openFiles();
                    } else {

                        var data = buff.toString('UTF-8');
                        self.parseNews(data, fileName);                             
                    }
                });

I know there are similar questions on SO, but none helped me... Could you help me in some way or address to a solution?

Thanks! Fabio

Upvotes: 2

Views: 5746

Answers (1)

robertklep
robertklep

Reputation: 203231

You need to specify the input encoding. Assuming that this.fs.readFile is the same as fs.readFile:

this.fs.readFile(fileName, { encoding : 'latin1' }, function(err, buff) {
  ...
  var data = buff.toString(); // no need to specify encoding here
});

Upvotes: 5

Related Questions