Node.js › File System & File Processing

How would you implement file locking in Node.js to prevent two processes from writing to the same file simultaneously?

Advanced

Answer

Node.js doesn't provide built-in cross-process file locking directly, so implementations typically use a third-party library (like proper-lockfile) that creates a separate lock file (or uses OS-level advisory locking where available) alongside the target file -- a process attempting to write first acquires the lock (waiting or failing if another process already holds it), performs its write, and then releases the lock, preventing concurrent, conflicting writes from corrupting the target file.
const lockfile = require('proper-lockfile');

const release = await lockfile.lock('shared-data.json');
try {
  const data = JSON.parse(await fs.promises.readFile('shared-data.json', 'utf-8'));
  data.count += 1;
  await fs.promises.writeFile('shared-data.json', JSON.stringify(data));
} finally {
  await release();
}
Real-world example Two separate cron jobs that both occasionally needed to update the same shared JSON state file were causing intermittent data corruption from concurrent writes, until the team added proper-lockfile-based locking to ensure only one process could write to the file at a time.

Common follow-ups: What happens if a process crashes while still holding a lock -- how do lock libraries typically handle stale lock recovery?;Would using a proper database instead of a shared file sidestep this problem entirely, and when is a file-based approach still preferable?