Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 646
Jan Moritz Avatar asked Feb 16 '14 17:02

Jan Moritz


People also ask

Can a file contain a null character?

The concept of NULL doesn't exist in a file, but within the generating app's programming language. Just the numeric encoding/value of NULL exists in a file. How is it possible that files can contain null bytes in operating systems written in a language with null-terminating strings (namely, C)?

What is null byte in file?

Null Byte Injection is an exploitation technique used to bypass sanity checking filters in infrastructure by adding URL. -encoded null byte characters (i.e., %00, or 0x00 in hex) to the user-supplied data.

Which of the following methods is used to write a file in node JS?

The fs. write() method is an inbuilt application programming interface of fs module which is used to specify the position in a file to begin writing at a buffer to write, as well as which part of the buffer to write out to the file.

How do you write data in a node js file?

The easiest way to write to files in Node. js is to use the fs. writeFile() API.


1 Answers

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

like image 150
loganfsmyth Avatar answered Nov 02 '22 21:11

loganfsmyth