Skip to content

fs: .writeFile(filehandle, ...) behavior differs from the documented one in all its variants #22554

@vsemozhetbyt

Description

@vsemozhetbyt

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.

  1. 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);
0
023
  1. 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);
      });
    });
  });
});
0
023

If this is intended behavior, should we make the description more accurate?

Metadata

Metadata

Assignees

No one assigned

    Labels

    fsIssues and PRs related to the fs subsystem / file system.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions