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

2

31

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 ?

Vie answered 13/12, 2012 at 11:49 Comment(0)
J
51

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) {});
Janeanjaneczka answered 13/12, 2012 at 11:51 Comment(3)
UTF-8 might not require a BOM in sane OSes and apps, but under Windows it just about always does. The exceptions are mostly cross-platform code ported from a sane environment.Meaningless
Fixed an issue where I was sending a CSV file to the client, worked well on Unix-like, not on Windaube. This fixed it!Gilbreath
I'm writing a text/csv file and using 'utf8' explicitly with the BOM like here, but it still won't display correctly when I open the file in Excel (without the whole import process but only opening the file). Any ideas why?Footway
U
1

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.

Unsnap answered 16/1, 2015 at 19:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.