The usual exec construct in node.js is:
exec('ls', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
Is it possible to insert stdout value to external variable like this:
var newLS = ''
exec('ls', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
newLS = stdout;
});
console.log(newLS)
If you try to use the above method, the "newLS" variable will not be changed. Is there any way to store the stdout value into an external variable?
There is a possible option:
newLS = exec('ls', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
console.log(newLS)
But in this case, newLS will store a large json (something like json) object with service information without the output itself.
Actual code:
app.post('/vmInfo', (req, res) => {
var string = JSON.stringify(req.body)
var objectValue = JSON.parse(string);
var vmInfo = {
ip: 'no information',
memoryUsage: 'no information'
}
exec('lxc list virtual1 -c "4" --format="csv"', (error, stdout, stderr) => {
});
exec('lxc list virtual1 -c "d" --format="csv"', (error, stdout, stderr) => {
});
res.send(vmInfo)
})
The task is to collect information from these two execs and put it into json.
The problem is, that exec is asynchronous, so you end up calling the external console.log, before the exec process has finished. You have to wait for the process to finish, before console.log.
Something like this should do the trick:
const newLS = await new Promise((resolve, reject) => {
exec('ls', (err, stdout, stderr) => {
if (err) {
console.error(err)
reject(err)
}
console.log(stdout)
resolve(stdout)
})
})
console.log(newLS)
Or you can use execSync
instead to make it a synchronous process.
EDIT:
Since OP said, that the exec was originally within an app.post()
, here the examples within app.post()
.
First the asynchronous version:
app.post('/', async (req, res) => {
const newLS = await new Promise((resolve, reject) => {
exec('ls', (err, stdout, stderr) => {
if (err) {
console.error(err)
reject(err)
}
console.log(stdout)
resolve(stdout)
})
})
console.log(newLS)
})
And second the synchronous version:
app.post('/', (req, res) => {
try{
newLS = execSync('ls')
console.log(newLS)
} catch (err) {
console.error(err)
}
})