Closed
Description
- Version: v6.11.0
- Platform: Darwin computer.local 16.6.0 Darwin Kernel Version 16.6.0: Fri Apr 14 16:21:16 PDT 2017; root:xnu-3789.60.24~6/RELEASE_X86_64 x86_64
- Subsystem: fs
Description:
#3163 added file descriptor support to *File() functions (for example fs.readFile
).
Issue: Writing then reading on the same FD does not read the data when using fs.readFile(fd)
. Only reading (witout writing) works as expected.
The demo opens a file descriptor, writes data to it and tries to read the data using the same FD and fs.readFile
. The demo code uses sync methods for simplicity, non-sync version has the same behavior.
const fs = require('fs');
const path = require('path');
const filepath = path.resolve(__dirname, './test-write-and-read.txt');
// 'w+' - Open file for reading and writing.
// The file is created (if it does not exist)
// or truncated (if it exists).
const fd = fs.openSync(filepath, 'w+');
// 'r+' - Open file for reading and writing.
// An exception occurs if the file does not exist.
// const fd = fs.openSync(filepath, 'r+');
// fs.writeFileSync(fd, 'foo bar'); // no issue
fs.writeSync(fd, 'FOOBAR'); // ISSUE: readFileSync(fd) will not read content
// fs.fsyncSync(fd); // <- seems to have no impact
// always reads content (no issue)
const buf = Buffer.alloc(20);
fs.readSync(fd, buf, 0, 20, 0);
console.log('read with fd:', buf.toString())
// always reads content (no issue)
console.log('readFileSync with filepath:', fs.readFileSync(filepath, { encoding: 'utf8' }));
// ISSUE: does not read content if previously writeSync(fd, 'foo bar')
console.log('readFileSync with fd:', fs.readFileSync(fd, { encoding: 'utf8' }));
fs.closeSync(fd);
Expected output:
read with fd: FOOBAR
readFileSync with filepath: FOOBAR
readFileSync with fd: FOOBAR
Actual output:
read with fd: FOOBAR
readFileSync with filepath: FOOBAR
readFileSync with fd:
(last line is missing the file content FOOBAR)
Note:
fs.fsync
seems to have no impact. Assuming this could help and flush the data to the filesystem- readFileSync with fd does successfully read data if previously no data has been written to the FD before and the test file contains content.