File locking
Deno.FsFile supports advisory file locking to coordinate access between processes:
- lock(exclusive?) — acquires a lock. Shared (read) by default; pass true for exclusive (write). Blocks if an incompatible lock is held.
- lockSync(exclusive?) — synchronous variant of lock().
- tryLock(exclusive?) — non-blocking. Returns true if the lock was acquired, false otherwise. Added in Deno 2.7.
- tryLockSync(exclusive?) — synchronous variant of tryLock().
const file = await Deno.open("./data.txt", { read: true, write: true });
const locked = await file.tryLock(true); // exclusive
if (locked) {
await file.write(new TextEncoder().encode("hello"));
await file.unlock();
} else {
console.log("File is locked by another process, skipping.");
}
file.close();