How to write a file with a "Byte Order Mark"?

Hello.
How to use the "file" node to write a file with a "Byte Order Mark" ?
Or how to do it using fs.writeFileSync() ?
I am grateful in advance.

Have you tried simply sending a buffer containing the BOM (and any other data) to a file write node.

Thank you for responding!
And how can a text string be converted to a buffer string to add '0hEF 0hBB 0hBF' (for UTF-8) to it ?
Or how do I convert '0hEF 0hBB 0hBF' to add to a text string ?

Using '0hEF 0hBB 0hBF' results in adding a string, not bytes.
How do I add exactly 3 bytes?

In the script below, I read the file from the BOM as a sample.
Then I try to create exactly the same Buffer.
But instead of a Buffer, I get an Object.
What is my mistake?

msg.payload = msg.payload;  // read file with BOM as binary  // => buffer[5]  Good !

var buffer = new ArrayBuffer(5);  //5 bytes
msg.payload_1 = buffer;  // => object empty   Why object ?

var intView = new Int8Array(buffer);  //8 bits
//intView = [0xEF,0xBB,0xBF,0x31,0x32];  //for UTF8 BOM=#EFBBBF 0x31,0x32=12
intView[0] = 0xEF;  //1byte BOM
intView[1] = 0xBB;  //2byte BOM
intView[2] = 0xBF;  //3byte BOM
intView[3] = 0x31;  //'1'
intView[4] = 0x32;  //'2'
msg.payload_2 = intView;  // => object: {"0":-17,"1":-69,"2":-65,"3":49,"4":50}

//buffer = new Uint8Array([0xEF,0xBB,0xBF,0x31,0x32]);
msg.payload_3 = buffer;  // => object empty   Why object ?

msg.filename = '/opt/12.txt';

return msg;

Use a node Buffer.

// using from
const buf1 = Buffer.from([0xEF,0xBB,0xBF,0x31,0x32])

// using alloc
const buf2 = Buffer.alloc(5)
buf2.writeUint8(0xEF,0)
buf2.writeUint8(0xBB,1)
buf2.writeUint8(0xBF,2)
buf2.writeUint8(0x31,3)
buf2.writeUint8(0x32,4)


Alternatively, use node-red-contrib-buffer-parser (it has a node named buffer-maker so you can do this in a low-code visual manner

1 Like

It's very important to me. Thank you the first time

It's important to me. Thank you the second time

It's important to me too. Thank you the third time

It's Useful to me. Thank you the fourth time

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.