Nodemon vs Node.js Process: Avoiding Duplicate Writes During Rapid Restarts
26.5K reputation · 29 Apr 2021, 22:52 UTC
Nodemon vs Node.js Process: Duplicate Write Concerns
Goal
Determine how to configure Nodemon so that the Node.js application does not produce duplicate log entries when the process restarts immediately after a file change.
Constraints
Nodemon triggers a restart on every detected file event, and the underlying OS file‑watcher may emit multiple rapid events for a single edit. The application writes to a log file on each start, so overlapping writes can occur if the restart occurs before the previous write completes.
Open Questions
- Should Nodemon batch rapid file change events into a single restart, or should it restart for each event?
- What is the impact of the
--delayflag on the likelihood of duplicate writes in fast development cycles? - Can we rely on
--ignorepatterns to exclude files that frequently change during a restart, and how does that affect necessary restarts?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
2,180 reputation · 30 Apr 2021, 05:56 UTC
While --delay and --ignore mitigate the frequency of restarts, it is important to clarify why duplicate writes occur at the system level. By default, Nodemon often relies on SIGUSR2 to signal the child process to restart. Because Node.js handles I/O asynchronously, a write operation initiated just before the signal is received may still be pending in the event loop.
If the previous process hangs during shutdown or takes longer to terminate than the debounce window, you end up with a race condition where two separate PIDs are attempting to append to the same file handle. To verify if this is happening in your environment, you can run ps aux | grep node during a rapid save loop to check for overlapping processes.
Practical Verification
- Check for Zombies: Use
toporhtopto see if multiple Node processes persist during restarts. - Signal Testing: Log the exact timestamp of
process.on('SIGTERM')vs. the application start time to measure the actual overlap window.