# 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 ```bt fs(path).atomic_write(content, expected_sha256) ``` ## Parameters | Parameters | Type | Required | Default value | Valid range | Description | | ------ | ------ | ------ | ------ | ------ | ------ | | content | Any | No | '' | BT value convertible to file content | New content to write; arrays and objects write JSON strings. | | expected_sha256 | String | No | None | 64-bit hex text | The 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. | Field | Type | Whether to always exist | Default value | Valid range | Meaning | | ------ | ------ | ------ | ------ | ------ | ------ | | bytes | Int | Yes | None | 0 and above | Number of bytes of new content. | | sha256 | String | Yes | None | 64-bit lowercase hexadecimal text | SHA-256 for new content. | | previous_sha256 | String/empty | Yes | empty | 64-bit lowercase hexadecimal text or empty | The SHA-256 that replaces the previous content; empty if the target did not originally exist. | ## Example ```bt file = fs('config.bt') old_hash = crypto(file.read()).sha256() result = file.atomic_write("name = 'BT 2'\n", old_hash) // Output: true print result.bytes > 0 ``` ## 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.