fs: harden `options` typecheck in reading methods
Can we have this on semver-patch
level?
This PR adds validation in fs.read() and filehandle.read() to make sure that first argument is a buffer or a params object (that is, not arbitrary-type value). In case of null
or undefined
, default values are used.
It also adds the same validation in fs.readSync(), which has a different signature: buffer
is not a part of options
object, but a mandatory first argument.
Currently, said methods are destructuring any non-ArrayBufferView value as { buffer, offset, position, length }
object.
For example, this happens without any warning if we accidentaly pass string or array (both have .length
property):
import {open} from 'fs/promises';
const fh = await open(process.argv[2], 'r');
const res = await fh.read('gwak'); // or [1, 2, 3, 4]
console.log('result:', res);
console.log('string:', String(res.buffer));
console.log('string length:', String(res.buffer).length);
$ cat /tmp/tst
ABCDEFGHI
$ node test.mjs /tmp/tst
result: {
bytesRead: 4,
buffer: <Buffer 41 42 43 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... 16334 more bytes>
}
string: ABCD
string length: 16384
With the patch:
$ node test.mjs /tmp/tst
node:internal/errors:475
ErrorCaptureStackTrace(err);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "options" argument must be of type object. Received type string ('gwak')
at read (node:internal/fs/promises:516:7)
at fsCall (node:internal/fs/promises:367:18)
at FileHandle.read (node:internal/fs/promises:168:12)
at file://test.mjs:3:22 {
code: 'ERR_INVALID_ARG_TYPE'
}
Node.js v18.0.0-pre