Learn how to write text in UTF-8 encoding with BOM in Node.js easily.

The UTF-8 BOM (Byte Order Mark) is a sequence of bytes placed at the start of a text stream that allows the reader to more reliably guess a file as being encoded in UTF-8. Normally, the BOM is used to signal the endianness of encoding, but since endianness is irrelevant to UTF-8, the BOM is unnecessary. However, there will be some cases where some clients will require text files to be opened on default text editors with the mentioned BOM. For example, you can determine whether a .txt file has BOM if you open it with Visual Studio Code:

Visual Studio Code UTF8BOM

In the bottom area, you will see that the default encoding used to read the file is UTF-8 with BOM and the editor was able to determine the encoding from its content. 

In this tutorial, I will explain to you how to write a file with the mentioned encoding in Node.js.

File with UTF-8BOM encoding

All that you need to do to add BOM to a file written with UTF-8 is to prepend \ufeff to the content. The following example will write 2 files using the default filesystem of Node.js, one will have the default UTF-8 and the other UTF-8 with BOM:

// Import FileSystem
const fs = require('fs');

// Regular Content of the file
let fileContent = "Hello World!";

// The absolute path of the new file with its name
let filepathUTF8 = "./utf8_file.txt";
let filepathUTF8WithBOM = "./utf8bom_file.txt";

// 1. Write a file with UTF-8
fs.writeFile(filepathUTF8, fileContent, (err) => {
    if (err) throw err;

    console.log("The file was succesfully saved with UTF-8!");
}); 

// 2. Write a file with UTF-8 with BOM
// Note that you prepend \ufeff to the content that will be written
fs.writeFile(filepathUTF8WithBOM, "\ufeff" + fileContent, (err) => {
    if (err) throw err;

    console.log("The file was succesfully saved with UTF-8 with BOM!");
}); 

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors