Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs - how to make function fs.writeFile write with BOM?

I'm using nodeJS v0.8.6 and the native library fs. Here is my code :

var filesys = require('fs'); filesys.writeFile('test.txt', 'This is an example with accents : é è à ','utf8', function (err) {}); 

The problem is that it writes in utf8 without BOM (I use notepad++ to verify it) and it doesn't work in wordpad on Windows (the accents are not well displayed). The thing is that I need that file to be well read by womeone using wordpad.

How can I add the BOM to my file ?

like image 446
user706355 Avatar asked Dec 13 '12 11:12

user706355


People also ask

Does fs writeFile create a file?

The fs. writeFileSync() creates a new file if the specified file does not exist.

What is the difference between fs writeFile and fs writeFileSync?

The fs. writeFileSync() is a synchronous method & creates a new file if the specified file does not exist while fs. writeFile() is an asynchronous method.

Which method of fs module is used to write?

The simplest way, and often the most appropriate, is to use the writeFile method in the fs module. This allows you to write to a specified file path, with asynchronous behavior, and creates a new file or replaces one if it exists at the path.


2 Answers

UTF-8 doesn't require a bom, but you can add it by yourself of course.

filesys.writeFile('test.txt', '\ufeffThis is an example with accents : é è à ','utf8', function (err) {}); 
like image 85
Esailija Avatar answered Sep 20 '22 18:09

Esailija


I elaborated on this answer in detail on this answer - Adding UTF-8 BOM to string/Blob.

This is a very sparse answer that doesn't go into detail as to why this works. The FEFF bytes are actually the UTF16LE BOM, so the previous answer is confusing.

like image 37
Jeff Fischer Avatar answered Sep 18 '22 18:09

Jeff Fischer