Why is it not possible to write a null byte in a file using ascii mode with node.js?
javascript, node.js
Solution
This isn't because of the file specifically, but rather then way Node converts ASCII into bytes to write. You'll see the same behavior in this:
new Buffer('\0', 'ascii')[0]
// 32
If you want to write a NULL byte to a file, don't use a string, just write the byte you want.
fs.writeSync(fp, new Buffer([0x00]));
Generally when doing file IO, I would recommend only using strings when the content is explicitly text content. If you are doing anything beyond that, stick with `Buffer`s.
Specifics
It is actually V8, not Node that performs this conversion. Node exposes the `ascii` encoding as a faster method of converting to binary. To achieve this, it uses V8's `String::WriteOneByte` method and unless explicitly instructed not to, this function automatically converts `'\0'` into `' '`.
Problem
This is my code ``` var fs = require('fs'); var fp = fs.openSync('binary.txt', "w"); var byte = '\0'; fs.writeSync(fp, byte, null, 'ascii'); ``` After executing it when I open the binary.txt file it contains 0x20 and not the null byte as expected. Now when I use ``` fs.writeSync(fp, byte, null, 'utf-8'); ``` I get the wanted null byte in the file.