If you read a file smaller than 8KB in size NodeJS allocates 8 KB for it.
This isn't intuitive or expected, we are getting "more" bytes than we put. But it isn't a bug either at least in the sense that it is documented.
Minimal NodeJS Example
const { Buffer } = require("node:buffer");
// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = Buffer.from(new Uint8Array([0, 1, 2, 3, 4]));
// size is 8KB, not 5 bytes.
console.log(nodeBuffer.buffer);
Question
- Why would 8KB buffer size be preferred over what we expect to have (the size of the data in the file.) ?
Files over 8KB would have an allocated space that matches the number of bytes in the file.
Other Details
I'm aware that we can use the offsets for reading:
// 1 KB
const buffer = fs.readFileSync(fileName, buffer.byteOffset, buffer.byteLength)
but the question isn't this.