Skip to content

fs: add WriteStream.prototype.fsync #28513

@bnoordhuis

Description

@bnoordhuis

Right now it's pretty complicated to intermix fs.fsync() calls with ws.write() calls, to the point that you lose most of the benefits of using fs.WriteStream. Example:

const fs = require('fs');
const ws = fs.createWriteStream('test.txt');
ws.write('important data', () => {
  fs.fsync(ws.fd, () => {
    // only now is it safe again to call ws.write()
    ws.write('more important data', () => {
      fs.fsync(ws.fd, () => { /* etc. */ });
    });
  });
});

It would be exceedingly helpful if fs.WriteStream grew a .fsync() method that preserves order with respect to writes so that the following example works like I would expect it to:

const ws = require('fs').createWriteStream('test.txt');
ws.write('important data');
ws.fsync();
ws.write('more important data');
ws.fsync();

It's not quite impossible to accomplish the above today but it's not very ergonomic. Here is an async/await example:

const util = require('util');
const fs = require('fs');
const ws = fs.createWriteStream('test.txt');
ws.once('open', (fd) => go(fd));
async function go(fd) {
  const write = util.promisify(ws.write.bind(ws));
  const fsync = util.promisify(fs.fsync.bind(null, fd));
  await write('important data');
  await fsync();
  await write('more important data');
  await fsync();
}

I don't know, the fact that you need to know about the 'open' event doesn't give me warm fuzzies. Proper synchronization is important enough that I feel it merits a place in core.

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues that request new features to be added to Node.js.fsIssues and PRs related to the fs subsystem / file system.stale

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions