Karthikeya Vaidya
Karthikeya Vaidya

Reputation: 121

How to determine if my JavaScript is running in nodejs

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

Upvotes: 0

Views: 54

Answers (2)

stdob--
stdob--

Reputation: 29172

Output stderr to log file and check it:

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

Upvotes: 0

gabesoft
gabesoft

Reputation: 1228

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

Upvotes: 1

Related Questions