最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is it not possible to write a null byte in a file using ascii mode with node.js? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 9

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 remend only using strings when the content is explicitly text content. If you are doing anything beyond that, stick with Buffers.

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 ' '.

发布评论

评论列表(0)

  1. 暂无评论