File System, Processes and Signals
Know how Node.js talks to the file system and the OS: which fs calls block, how paths resolve, how processes start, exit and receive signals, and how to run child processes and shut down safely in containers.
Key points
- 1
Sync fs calls block the whole event loop. Use them at startup or in CLIs, and use
fs/promisesor streams inside servers; stream large files instead ofreadFile. - 2
Relative fs paths resolve against
process.cwd(), not the module. Build paths from__dirname(CommonJS) orimport.meta.dirname(ESM, Node.js 20.11+).path.joinconcatenates;path.resolverestarts at the last absolute segment. - 3
Avoid check-then-act races: open with the
wxflag instead ofexistsSync+ write, and write atomically with a temp file in the same folder plusrename(renaming across filesystems fails with EXDEV). - 4
Prefer
process.exitCodeoverprocess.exit(): exit() abandons timers and pending stdout writes. Theexitevent only runs synchronous code;beforeExitcan schedule more work. - 5
Signals: SIGINT and SIGTERM exit with 128 + signal (130, 143) unless you add a listener, which removes the default. As PID 1 in a container, Node.js ignores SIGTERM unless it handles it; use the exec form of CMD and
--init. - 6
child_process:
execuses a shell and buffers up tomaxBuffer(1 MiB);execFileandspawntake argument arrays without a shell;forkadds an IPC channel. Consume piped stdout, and usedetached+unref()for background children. - 7
Built-ins replace common packages:
--env-file(environment values win, later files override),util.parseArgs(strict by default),--watch,node:sqlite, and the opt-in--permissionmodel.
Common traps
target.startsWith(base)is not a path traversal check:/srv/uploads-oldpasses for base/srv/uploads. Usepath.relativeand reject results starting with...child.kill()signals only the direct child. Servers started through npm or a shell survive as orphans and keep their ports.fs.watchon a single file stops seeing changes after an editor's atomic save, because it watches the old inode. Watch the directory instead.
Read the source
Test yourself on File System, Processes and Signals
Ten questions, with the answer and explanation after each one.