Here is the code I'm using:
const { exec } = require("child_process");
exec("ls -la", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
It returns "0" and then logs in the console the correct result.
But how to directly return
the result instead of console.log
?
Some answers have pointed out how to convert it into a Promise.
The problem you are experiencing is that it takes time to run an OS command (perhaps indefinite amount of time). Javascript will not just halt execution until this is done, so it is run asynchronously.
A value must be returned and must be returned to the caller before it completes. Using promises, the value returned is a promise.
Since you are calling with the Construct 2 Engine which does not have a mechanism for asynchronous calls, you will not get a result directly.
However, Construct 2 engine has a mechanism for calling back into it, using the
Function object
Your javascript should look like this:
you can execute like this :
But, to get the results, you must define a Function object called 'lsresult', add parameters to the function (error, stdout, stderr) and handle the results there.
Documentation is here: https://www.construct.net/en/construct-2/manuals/construct-2/plugin-reference/function