admin管理员组文章数量:1317364
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.
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.
Share Improve this question edited Aug 3, 2014 at 2:08 Jan Moritz asked Feb 16, 2014 at 17:32 Jan MoritzJan Moritz 2,2254 gold badges25 silver badges34 bronze badges1 Answer
Reset to default 9This 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 remend 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 ' '
.
版权声明:本文标题:javascript - Why is it not possible to write a null byte in a file using ascii mode with node.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742019566a2414415.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论