I am executing shell script commands from my nodejs script. One of these commands is "npm install" followed by a command to run the index file of a nodejs file.
The npm install command is returning an error generated by node-gyp. In general, this error does not affect my service. However, child_process.exec is catching it and stopping the script. My questions is, how do I trigger the exec command and ignore the error returned?
Below is a fraction of the code snippet
const exec = require('child_process').exec;
exec("npm install", {
cwd: serviceDirectory + gitRepo
},
(error1, stdout, stderr) => {
if(error1){
//this error is for testing purposes
util.log(error1);
}
//run the service
exec("node index.js",{
cwd: serviceDirectory + gitRepo + "/"
}, cb);
});
}
You can use try-catch to handle the errors with catch, example:
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
export default async function () {
const dataFormat = {
stdout: '',
stderr: '',
};
let cpu = dataFormat;
let diskUsed = dataFormat;
try {
cpu = await exec('top -bn1 | grep "Cpu(s)" | sed "s/.*, *\\([0-9.]*\\)%* id.*/\\1/"');
} catch (error) {
cpu.stderr = error.stderr;
}
try {
diskUsed = await exec("df -h | awk 'NR==2{printf $3}'");
} catch (error) {
diskUsed.stderr = error.stderr;
}
const payload = {
cpu,
diskUsed,
};
return payload
}
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.