Does Deno.writeTextFile acquire a lock? #26692
-
My original code looked like this: await Deno.writeTextFile(path, data); But then it occurred to me that it's really important that multiple Deno processes don't try to write the file at the same time. Thus, I need to acquire a lock. So I rewrote the code: using file = await Deno.open(path, { write: true, create: true });
await file.lock(true);
const buffer = new TextEncoder().encode(data);
const writer = file.writable.getWriter();
await writer.write(buffer);
await writer.close(); But then I wondered, is it possible that |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It does not, which you can confirm by calling By the way, you forgot to const tempFile = await Deno.makeTempFile({ dir: dirname(path) });
try {
await Deno.writeTextFile(tempFile, data);
await Deno.rename(tempFile, path);
} catch (e) {
await Deno.remove(tempFile);
throw e;
} |
Beta Was this translation helpful? Give feedback.
It does not, which you can confirm by calling
writeTextFile
while the file is exclusively locked.By the way, you forgot to
truncate
the file after locking it. In case lock contention turns out to be a problem, another way to rewrite a file atomically is to write all data into a temporary file and then replace the original file using a rename.