1'use strict'; 2 3const common = require('../common'); 4 5// The following tests validate base functionality for the fs.promises 6// FileHandle.read method. 7 8const fs = require('fs'); 9const { open } = fs.promises; 10const path = require('path'); 11const fixtures = require('../common/fixtures'); 12const tmpdir = require('../common/tmpdir'); 13const assert = require('assert'); 14const tmpDir = tmpdir.path; 15 16tmpdir.refresh(); 17 18async function validateRead() { 19 const filePath = path.resolve(tmpDir, 'tmp-read-file.txt'); 20 const fileHandle = await open(filePath, 'w+'); 21 const buffer = Buffer.from('Hello world', 'utf8'); 22 23 const fd = fs.openSync(filePath, 'w+'); 24 fs.writeSync(fd, buffer, 0, buffer.length); 25 fs.closeSync(fd); 26 const readAsyncHandle = await fileHandle.read(Buffer.alloc(11), 0, 11, 0); 27 assert.deepStrictEqual(buffer.length, readAsyncHandle.bytesRead); 28 assert.deepStrictEqual(buffer, readAsyncHandle.buffer); 29} 30 31async function validateEmptyRead() { 32 const filePath = path.resolve(tmpDir, 'tmp-read-empty-file.txt'); 33 const fileHandle = await open(filePath, 'w+'); 34 const buffer = Buffer.from('', 'utf8'); 35 36 const fd = fs.openSync(filePath, 'w+'); 37 fs.writeSync(fd, buffer, 0, buffer.length); 38 fs.closeSync(fd); 39 const readAsyncHandle = await fileHandle.read(Buffer.alloc(11), 0, 11, 0); 40 assert.deepStrictEqual(buffer.length, readAsyncHandle.bytesRead); 41} 42 43async function validateLargeRead() { 44 // Reading beyond file length (3 in this case) should return no data. 45 // This is a test for a bug where reads > uint32 would return data 46 // from the current position in the file. 47 const filePath = fixtures.path('x.txt'); 48 const fileHandle = await open(filePath, 'r'); 49 const pos = 0xffffffff + 1; // max-uint32 + 1 50 const readHandle = await fileHandle.read(Buffer.alloc(1), 0, 1, pos); 51 52 assert.strictEqual(readHandle.bytesRead, 0); 53} 54 55validateRead() 56 .then(validateEmptyRead) 57 .then(validateLargeRead) 58 .then(common.mustCall()); 59