Function return not work

Hi all, I'm writing a function in func-exec node

msg.topic = ""
var array = [];

var exec = child_process.exec('pgrep firefox', (error, stdout, stderr) => {
    if (error) { 
        console.info("false")
        msg.payload = false 
        msg.topic = "error connection ui"
        return msg;
    } 
    if (stdout != ""){
        var splitString = stdout.split(" ")
        for (var i = 0; i < splitString.length; i++){
            array.push(parseInt(splitString[i]))
        }
        console.info(array)
        msg.payload = array
    }
}); 
console.info(msg.payload)
return msg;

unfortunately the msg.payload is always undefined while array is corrected not empty as I can see on the console.

can some help me to understand where I wrong?
many thanks

does the second if () require a return?

Hi @denissanga

You cannot use return to send a message from inside a callback function - you can only use return at the top level of the code.

To send a message from inside a callback, you need to use node.send(msg) - Writing Functions : Node-RED

many thanks

I try with this

msg.topic = ""
var array = [];

var exec = child_process.exec('pgrep firefox', msg, (error, stdout, stderr) => {
    if (error) { 
        console.info("false")
        msg.payload = false 
        msg.topic = "error connection ui"
        node.send(msg)
    } 
    if (stdout != ""){
        var splitString = stdout.split(" ")
        for (var i = 0; i < splitString.length; i++){
            array.push(parseInt(splitString[i]))
        }
        console.info("out1  " + array)
        msg.payload = array
        node.send(msg)
    }
}); 


console.info("out2  " + msg.payload)
return msg;

but I obtain
out1 123345
out2 true

What do you expect to get?

If you only want it to send a message once the exec has finished, then delete the return msg line at the end.

I would obtain 123345...there is no way with this approach?

I do not understand what you mean.

You have said you are getting:

out1 12324123

That tells us the console.info you have inside the callback is being called... so we can assume the next two lines are also being called which will cause a message to be sent:

msg.payload = array
node.send(msg)

Have you connected a Debug node to the output of the Function to see what message it is sending?

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