0

I have a script which has some program logic. I run this script using nodejs for real-time communication between server and clients. Sometime due to some errors nodejs stops and script fails to run. This is how I run my script

nodejs myscript.js

Now in this script if I have some error (lets say some undefined variable) Nodejs stops running and throws an error

ReferenceError: abcd is not defined
at WebSocket.open (/var/nodes/myserver/myscript.js:99:54)
at WebSocket.emit (events.js:92:17)

Now how can I find out that my script stopped running because of some error?? I am sure that there is someway to achieve this. If this is not possible then I am ok to run another script (lets say watch.js) to have a track on myscript.js. But how to do this??

Thank You

2
  • nodejs myscript.js ; echo "The End." Commented Mar 17, 2016 at 6:32
  • PM2 could be one tool to monitor it. Commented Mar 17, 2016 at 6:35

2 Answers 2

1

A node process has an uncaughtException event which you can handle

process.on('uncaughtException', (err) => {
  console.log(`Caught exception: ${err}`);
});

See more details here https://nodejs.org/api/process.html#process_event_uncaughtexception

Sign up to request clarification or add additional context in comments.

2 Comments

Bad practice. Your app in undefined state, you should terminate the process in callback anyway.
Right but before you terminate you can log to console or do some other cleanup
0

Output stderr to log file and check it:

node myscript.js 2>>"log/`date +"%Y-%m-%d %T-%N"`.log"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.