Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fs: Make parameters optional for readSync
* This makes the offset, length and position parameters optional by
passing in an options object.
  • Loading branch information
lholmquist committed Mar 30, 2020
commit c91f09e3cd640def5148eefec33d2749184bf489
14 changes: 14 additions & 0 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -533,8 +533,22 @@ function read(fd, buffer, offset, length, position, callback) {
ObjectDefineProperty(read, internalUtil.customPromisifyArgs,
{ value: ['bytesRead', 'buffer'], enumerable: false });

// usage:
// fs.readSync(fd, buffer, offset, length, position);
// OR
// fs.readSync(fd, buffer, {}) or fs.readSync(fd, buffer)
function readSync(fd, buffer, offset, length, position) {
validateInt32(fd, 'fd', 0);

if (arguments.length <= 3) {
// Assume fs.read(fd, buffer, options)
const options = offset || {};

offset = options.offset || 0;
length = options.length || buffer.length;
position = options.position;
}

Comment thread
lholmquist marked this conversation as resolved.
Outdated
validateBuffer(buffer);

if (offset == null) {
Expand Down
34 changes: 34 additions & 0 deletions test/parallel/test-fs-readSync-optional-params.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';

require('../common');
const fixtures = require('../common/fixtures');
const fs = require('fs');
const assert = require('assert');
const filepath = fixtures.path('x.txt');
const fd = fs.openSync(filepath, 'r');

const expected = Buffer.from('xyz\n');
const defaultBuffer1 = Buffer.allocUnsafe(expected.length);
const defaultBuffer2 = Buffer.allocUnsafe(expected.length);
const defaultBuffer3 = Buffer.allocUnsafe(expected.length);

// Test passing in an empty options object
const result1 = fs.readSync(fd, defaultBuffer1, { position: 0 });
assert.strictEqual(result1, expected.length);
assert.deepStrictEqual(defaultBuffer1, expected);

// Test not passing in any options object
const result2 = fs.readSync(fd, defaultBuffer2);
assert.strictEqual(result2, expected.length);
assert.deepStrictEqual(defaultBuffer2, expected);


// Test passing in options
const result3 = fs.readSync(fd, defaultBuffer3, {
offset: 0,
lenght: defaultBuffer3.length,
Comment thread
lholmquist marked this conversation as resolved.
Outdated
position: 0
});

assert.strictEqual(result3, expected.length);
assert.deepStrictEqual(defaultBuffer3, expected);