2020-03-24 15:23:33 +00:00
|
|
|
'use strict';
|
|
|
|
|
2022-07-24 13:29:06 +00:00
|
|
|
const { mustNotMutateObjectDeep } = require('../common');
|
2020-03-24 15:23:33 +00:00
|
|
|
const fixtures = require('../common/fixtures');
|
|
|
|
const fs = require('fs');
|
|
|
|
const assert = require('assert');
|
|
|
|
const filepath = fixtures.path('x.txt');
|
|
|
|
|
|
|
|
const expected = Buffer.from('xyz\n');
|
|
|
|
|
2022-04-19 06:19:55 +00:00
|
|
|
function runTest(defaultBuffer, options, errorCode = false) {
|
2022-02-27 12:56:09 +00:00
|
|
|
let fd;
|
|
|
|
try {
|
|
|
|
fd = fs.openSync(filepath, 'r');
|
2022-04-19 06:19:55 +00:00
|
|
|
if (errorCode) {
|
|
|
|
assert.throws(
|
|
|
|
() => fs.readSync(fd, defaultBuffer, options),
|
|
|
|
{ code: errorCode }
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
const result = fs.readSync(fd, defaultBuffer, options);
|
|
|
|
assert.strictEqual(result, expected.length);
|
|
|
|
assert.deepStrictEqual(defaultBuffer, expected);
|
|
|
|
}
|
2022-02-27 12:56:09 +00:00
|
|
|
} finally {
|
|
|
|
if (fd != null) fs.closeSync(fd);
|
|
|
|
}
|
2020-03-24 15:23:33 +00:00
|
|
|
}
|
|
|
|
|
2022-02-27 12:56:09 +00:00
|
|
|
for (const options of [
|
2020-03-24 15:23:33 +00:00
|
|
|
|
2022-02-27 12:56:09 +00:00
|
|
|
// Test options object
|
|
|
|
{ offset: 0 },
|
|
|
|
{ length: expected.length },
|
|
|
|
{ position: 0 },
|
|
|
|
{ offset: 0, length: expected.length },
|
|
|
|
{ offset: 0, position: 0 },
|
|
|
|
{ length: expected.length, position: 0 },
|
|
|
|
{ offset: 0, length: expected.length, position: 0 },
|
2020-03-24 15:23:33 +00:00
|
|
|
|
2022-02-27 12:56:09 +00:00
|
|
|
{ position: null },
|
|
|
|
{ position: -1 },
|
|
|
|
{ position: 0n },
|
|
|
|
|
|
|
|
// Test default params
|
|
|
|
{},
|
|
|
|
null,
|
|
|
|
undefined,
|
|
|
|
|
2022-04-19 06:19:55 +00:00
|
|
|
// Test malicious corner case: it works as {length: 4} but not intentionally
|
|
|
|
new String('4444'),
|
|
|
|
]) {
|
|
|
|
runTest(Buffer.allocUnsafe(expected.length), options);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const options of [
|
|
|
|
|
|
|
|
// Test various invalid options
|
2022-02-27 12:56:09 +00:00
|
|
|
false,
|
|
|
|
true,
|
|
|
|
Infinity,
|
|
|
|
42n,
|
|
|
|
Symbol(),
|
2022-04-19 06:19:55 +00:00
|
|
|
'amString',
|
|
|
|
[],
|
|
|
|
() => {},
|
2022-02-27 12:56:09 +00:00
|
|
|
|
2022-04-19 06:19:55 +00:00
|
|
|
// Test if arbitrary entity with expected .length is not mistaken for options
|
2022-02-27 12:56:09 +00:00
|
|
|
'4'.repeat(expected.length),
|
|
|
|
[4, 4, 4, 4],
|
|
|
|
]) {
|
2022-04-19 06:19:55 +00:00
|
|
|
runTest(Buffer.allocUnsafe(expected.length), mustNotMutateObjectDeep(options), 'ERR_INVALID_ARG_TYPE');
|
2022-02-27 12:56:09 +00:00
|
|
|
}
|