Run line at node script end?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Node.js, "run something at the end of the script" can mean two different things: run code after your own logic finishes, or run code when the process is about to exit. Those cases are not the same, especially once asynchronous work enters the picture.
The Simplest Case: Put the Line Last
If your script is fully synchronous, the last line already runs at the end:
That stops being enough as soon as you add file I/O, timers, database calls, or network requests. Node will keep the process alive while pending work exists, so the "end" of the file is not necessarily the end of the program.
Prefer try and finally Around Your Main Logic
If you control the script, the cleanest pattern is usually to wrap the main flow and use finally for cleanup.
This is usually what people actually want. The cleanup line runs after main resolves or rejects, and it still works with asynchronous code.
If you need to guarantee cleanup around part of the logic, try and finally inside main is even clearer:
Use Process Events Only for Process-Level Behavior
Node also exposes lifecycle events on process, especially beforeExit and exit.
These events are useful, but they come with rules:
- '
beforeExitfires when Node has no more work scheduled' - '
exitfires immediately before shutdown' - you should not expect asynchronous cleanup inside
exitto complete
That last rule is critical. If you do this:
the timer callback will never execute. The process is already exiting.
Handle Interruptions Explicitly
Sometimes "script end" really means "the user pressed Control+C" or the process received a termination signal. In that case, listen for signals rather than only relying on normal completion.
This is the right place for shutdown messages, closing open connections, or marking a job as interrupted.
Choose the Right Pattern
Use the last line of the file when everything is synchronous. Use finally when you want cleanup after a controlled operation. Use process.on("exit") only for small synchronous shutdown work. Use signal handlers for termination from outside the script.
That separation keeps the script predictable:
- application logic owns its own cleanup
- process events handle process lifecycle
- signal handlers handle interruptions
Once you treat those as different tools, the confusion disappears.
Common Pitfalls
- Assuming the last line of the file runs after asynchronous work. It only runs after the current synchronous turn.
- Doing asynchronous work inside the
exithandler. Node does not wait for it. - Calling
process.exit()too early. That can terminate the process before logs flush or cleanup finishes. - Using process events when a local
tryandfinallywould be simpler and safer. - Forgetting about signals such as
SIGINTwhen the real requirement is graceful shutdown on interruption.
Summary
- In a synchronous script, the last line is the end.
- In an asynchronous script, use
tryandfinallyor promise.finally()for cleanup. - '
beforeExitandexitare process lifecycle hooks, not a substitute for normal control flow.' - Keep
exithandlers synchronous because asynchronous callbacks will not finish there. - If you need graceful shutdown on interruption, listen for signals such as
SIGINT.
Related reading
- Run react-native application on iOS device directly from command line?
- Run script before iframe loads
- Run two async functions without blocking each other
- Running javascript from within Asynchronous Content with hinclude in symfony 2
- Running multiple async tasks and waiting for them all to complete
- Running multiple async tasks and waiting for them all to complete
- Running Python on Windows for Node.js dependencies
- Runtime.ImportModuleError trying to access npm package in an AWS lambda function using layers
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.