I got a bash script, which output a integer value and how do I grab that value as a variable.
var exec = require('child_process').exec;
var ftpsize;
exec('~/docker-project/ftp.check.sh',
function (error, stdout, stderr) {
if (error !== null) {
console.log(error);
} else {
ftpsize=stdout;
console.log('stdout: ' stdout);
console.log('stderr: ' stderr);
}
});
console.log('stdout: ' ftpsize);
stdout: 889951 and ftpsize as undifined, how do I extract the stdout as variable.
CodePudding user response:
Because the callback that run after ftp.check.sh
execute is called asynchronously, ftpsize
will be undefined because the order of execution is:
- start
exec
console.log('stdout: ' ftpsize);
-> undefinedexec
complete,ftpsize=stdout;
What you may want to look at is the concept of a "promise" in javascript. But, long story short, you want to define a function that return a "future value", and then you want to "await" for it to complete.
async function run() {
return new Promise((resolve, reject) => {
exec('~/docker-project/ftp.check.sh', function (error, stdout, stderr) {
if (error !== null) {
console.log(error);
reject(error)
return
}
console.log('stdout: ' stdout);
console.log('stderr: ' stderr);
resolve(stdout)
})
})
}
which you can then consume with const ftpsize = await run()
or run().then(ftpsize => { /* ... */ })