Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - unable to create utf-8 file

Tags:

node.js

utf-8

I have created file using this command

   var fs = require('fs');
    fs.appendFile('log.csv', 'Hello','utf-8',  function (err) {
        if (err) throw err;
    });

Now when i check the encoding of file

file -bi log.csv

The result is

text/plain; charset=us-ascii

How do I create a utf-8 encoded file?

like image 634
Sarita Avatar asked Dec 10 '22 16:12

Sarita


1 Answers

I think there are two things here. First you have specified utf8 incorrectly. It should be

fs.appendFile('message.txt', 'data to append', 'utf8', callback);

That is taken from the docs here

utf8 is actually the default, so you shouldn't even need to pass it as an option

What is new to me, however, is that seemingly you have to write utf to the file for it to appear encoded as UTF-8

var fs = require('fs');

fs.appendFile('log.csv', '\ufeffThis is an example with accents : é è à ', 'utf8', function(err) {
    if (err) throw err;
});

now we see

$ file -I log.csv
$ log.csv: text/plain; charset=utf-8
like image 135
Philip O'Brien Avatar answered Dec 31 '22 16:12

Philip O'Brien