fs.atomic_write

fs.atomic_write

fs.atomic_write

Function

First write the new content to a temporary file in the same directory as the target and flush it to the disk, then atomically replace the target file; you can use SHA-256 of the old content to detect external modifications to avoid silent overwriting.

Syntax

Parameters

ParametersTypeRequiredDefault valueValid rangeDescription
contentAnyNo''BT value convertible to file contentNew content to write; arrays and objects write JSON strings.
expected_sha256StringNoNone64-bit hex textThe SHA-256 of the target's existing content; when passed in, it will be verified before creating the temporary file and before final replacement.

Return value

Return Object.

FieldTypeWhether to always existDefault valueValid rangeMeaning
bytesIntYesNone0 and aboveNumber of bytes of new content.
sha256StringYesNone64-bit lowercase hexadecimal textSHA-256 for new content.
previous_sha256String/emptyYesempty64-bit lowercase hexadecimal text or emptyThe SHA-256 that replaces the previous content; empty if the target did not originally exist.

Example

Notes

  • The target parent directory must exist, the target cannot be a directory.
  • The temporary file and the target are in the same directory; the target is replaced only after the temporary contents are completely written and flushed.
  • When expected_sha256 is passed in, a conflict will be reported if the target does not exist, the digest does not match, or it is modified externally during writing, and the original content will not be silently overwritten by the new content.
  • Windows uses atomic replacement with write penetration; other platforms use the same file system rename.