goodvibration
goodvibration

Reputation: 6206

How can I ensure that 'fs.appendFileSync' never succeeds partially?

Up until now, my assumption has been that if fs.appendFileSync throws an exception, then it is guaranteed that the contents of the target file haven't changed one bit.

The official documentation of this function doesn't refer to this issue (and to failure cases in general).

The source code of this function shows that it calls fs.writeFileSync, which in turn does this:

  try {
    while (length > 0) {
      const written = fs.writeSync(fd, data, offset, length, position);
      offset += written;
      length -= written;
      if (position !== null) {
        position += written;
      }
    }
  } finally {
    if (!isUserFd) fs.closeSync(fd);
  }

Can I infer from the above that fs.appendFileSync may throw an exception after partially changing the target file?

If yes, then are there any known tools or paradigms for tackling this rather-difficult-to-handle situation?

Upvotes: 0

Views: 79

Answers (1)

MattDiMu
MattDiMu

Reputation: 5013

Yes, fs.appendFileSync doesn't support any form of transactions afaik. While i do not know any partical nodeJS-module for this use case, you could do it manually by

  • duplicating the file
  • appending to the duplicate tmp-file
  • renaming/replacing the original file with the tmp file

Upvotes: 1

Related Questions