Search code examples
javascriptnode.jsutf-8utf-16ucs2

How to convert a UTF16 file into a UTF8 file in nodejs


I have an xml file encoded in UTF16, and I would like to convert it to UTF8 in order to process it. If I use this command:

iconv -f UTF-16 -t UTF-8 file.xml > converted_file.xml

The file is converted correctly and I'm able to process it. I want to do the same in nodejs.

Currently I have a buffer of my file and I've tried everything I could think of and what I could find on the internet but unsuccessfully.

Here is some examples of what I've tried so far:

content = new Buffer((new Buffer(content, 'ucs2')).toString('utf8'));

I've also tried using those functions:

http://jonisalonen.com/2012/from-utf-16-to-utf-8-in-javascript/ https://stackoverflow.com/a/14601808/1405208

The first one doen't change anything and the links only give me chinese characters.


Solution

  • var content = fs.readFileSync('myfile.xml', {encoding:'ucs2'});
    fs.writeFileSync('myfile.xml', content, {encoding:'utf8'});