Check if message.status.text exists

Hi,
I am using a status node to check if an exec is running. If the exec is started or killed the status is known.
However if the exec has not been started or killed, the message.status.text doesn't exist and then I get an error.
I did try this function but it doesn't work.

if ((msg.status.text) !== undefined)
  var test = msg.status.text;
  msg.payload = "something....."

the error is: "TypeError: Cannot read properties of undefined (reading 'text')"

How do you detect if msg.status.text is undefined?

Thanks for helping

I'm not an expert.

if ((msg.status.text) !== undefined)
  var test = msg.status.text;
  msg.payload = "something....."

I think you need to use { } around it.
But there again, maybe not.
Just your formatting - to me - is confusing.

Implies you want to do this:

if ((msg.status.text) !== undefined)
{
  // not set.
  var test = msg.status.text;
  msg.payload = "something....."
}
//  Now it is set.

Maybe:
But it could be

if ((msg.status.text) !== undefined)
{
  // If not defined.
  var test = msg.status.text;
}  //  If it is defined.
msg.payload = "something....."

But you may need to post a bit more of the code.
Because I am not seeing how/where test is used/needed.

Maybe - in retrospect:

if ((msg.status.text) !== undefined)
{
  // If not defined.
  msg.status.text = "Not defined";
}  //  If it is defined.
// msg.status.text is defined and can now be handled downstream from here. 

But I don't know exactly if this will help or not.

if (msg.status?.text !== undefined) {
    ...
}

Thanks for highlighting the missing braces. It was a copy past mistake.
this is the correct one:

if ((msg.status.text) !== undefined) {
  var test = msg.status.text;
  msg.payload = "Process not running"
}

return msg;

the issue is that the condition "undefined" is wrong. The code still try to read the msg.status.text which doesn't exists.

But where is test used?

Can you post a bit more of the flow?

Maybe like the exec node and status node?

This seems to give a different result. Let me investigate it better. Thanks for now...

Perhaps I should have given some more details:

Your initial check stumbles over the fact that you can test for .text only if .status exists.
Yet if .status is missing, it's obvious that .text will be undefined as well.

How's ?. (optional chaining) working?

The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called is undefined or null, it returns undefined instead of throwing an error.

1 Like

Thanks a million for the solution and for the explanation. It is now working correctly.

1 Like

Good to hear!

It's nice when you get a solid answer to a question/problem.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.