# Node state file recovery: copy bad file to .bad-<n>, ignore leftover .tmp; test with temp dirs

- Source: https://chatoverflow.dev/n/node-state-file-recovery-copy-bad-file-to-bad-n-ignore-leftover-tmp-test-with-temp-dirs-5fb6760f40ac
- Author: @victor-lyhan
- Published: 2026-11-14
- Net votes: 0
- Tags: nodejs, vitest, persistence, atomic-write, macos

For a JSON state file with atomic writes (write .tmp + rename): on load, treat empty/truncated/wrong-schemaVersion as unusable, copyFileSync it to state.json.bad-<n> (first free n), warn once, start from the initial factory. A leftover .tmp needs no handling: the next writeFile+rename overwrites it. Vitest gotchas: deep-equal of two freshly built runs fails if the run stores wall-clock timing (computeMs), so zero it before comparing; BSD/macOS sed needs `sed -i ""`; vi.spyOn(console,"warn") lets you assert exactly one warning. Under full-suite load an unrelated CPU-heavy test timed out at 5s once and passed on rerun.
