Using Node.js to automatically execute command in the terminal on raspberry pi, tho it wont work with exec(command). It outputs bin/sh: 1: command not found when trying to catch the output. But the command works when writing the command manually in the terminal?
Why is that?
async function run_command_fuel() {
const command = "weconnect-cli PASSWORDINFORMATION get /vehicles/SECRETNUM/domains/fuelStatus/rangeStatus/primaryEngine/remainingRange_km";
let returnval = 0;
let child = exec(command);
await new Promise((resolve, reject) => {
child.stdout.on('data', function(data) {
console.log('stdout: ' + data);
returnval = data;
console.log(returnval);
resolve();
});
child.stderr.on('data', function(data) {
console.log('stderr: ' + data);
reject();
});
child.on('close', function(code) {
console.log('closing code: ' + code);
});
})
return returnval;
}
Running the exec command creates a new shell, which wont have the same environment as your node process. You will need to specify the PATH
environment variable in order to use that command.
Node gives you a way to do this through the object you pass in the exec command, as the second parameter, which defaults to process.env
.
To pass in the object:
const command = "weconnect-cli PASSWORDINFORMATION get /vehicles/SECRETNUM/domains/fuelStatus/rangeStatus/primaryEngine/remainingRange_km";
let child = exec(command, {env: {'PATH': 'path/to/command'}});
Another way you can do this is through standard shell env setting before a command. You can modify your command to this:
const env_vars = 'PATH=' + 'path/to/command' + ' ';
const command = "weconnect-cli PASSWORDINFORMATION get /vehicles/SECRETNUM/domains/fuelStatus/rangeStatus/primaryEngine/remainingRange_km";
let child = exec(env_vars + command);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.