import {promises as fsp} from "fs" export function nodeSafeFileOperations(path: string) { let operationChain: Promise> = Promise.resolve(undefined) async function load(): Promise> { try { const text = await fsp.readFile(path, "utf8") const entries = JSON.parse(text) return new Map(entries) } catch (error) { return new Map() } } async function save(map: Map) { const entries = Array.from(map.entries()) const text = JSON.stringify(entries, undefined, "\t") await fsp.writeFile(path, text, "utf8") } return async function operation( action: (map: Map) => Promise> = async() => undefined ) { operationChain = operationChain.then(async() => { const map = await load() const changes = await action(map) if (changes) await save(map) return map }) return operationChain } }