fs: `.writeFile(filehandle, ...)` behavior differs from the documented one in all its variants
Currently, the fs.writeFile[Sync]() description states:
Asynchronously writes data to a file, replacing the file if it already exists.
However, this is only true if the first argument is a filename. If it is a file descriptor, the file content is not truncated (as somebody may expect) and a new data is merged from the 0 position into the old data.
- Compare
fs.readFileSync()behavior:
'use strict'; const fs = require('fs'); const fileName = 'test.txt'; fs.writeFileSync(fileName, '123'); fs.writeFileSync(fileName, '0'); console.log(fs.readFileSync(fileName, 'utf8')); fs.unlinkSync(fileName); const fd = fs.openSync(fileName, 'w'); fs.writeFileSync(fd, '123'); fs.writeFileSync(fd, '0'); fs.closeSync(fd); console.log(fs.readFileSync(fileName, 'utf8')); fs.unlinkSync(fileName);
- Compare the same
fs.writeFile()behavior:
const fs = require('fs'); const fileName = 'test.txt'; fs.writeFile(fileName, '123', () => { fs.writeFile(fileName, '0', () => { console.log(fs.readFileSync(fileName, 'utf8')); fs.unlinkSync(fileName); const fd = fs.openSync(fileName, 'w'); fs.writeFile(fd, '123', () => { fs.writeFile(fd, '0', () => { fs.closeSync(fd); console.log(fs.readFileSync(fileName, 'utf8')); fs.unlinkSync(fileName); }); }); }); });
If this is intended behavior, should we make the description more accurate?