I have a auto-created JS file. And my module call it, some time the auto-created JS file cause infinite loop. And i will call thousand of auto-created JS file, some will run correct but some will cause infinite loop and I will don't know about file content
==> I wonder how I can handle this ?
Example of auto-created JS file. It name "excute.js"
const excuted = (a,b) => {
let i = 0;
while(a<b){
i++;
}
console.log(i);
}
module.exports = excuted();
Example My module ==> i want handle infinite loop error here
const {exec} = require("child_process");
const check = () => {
exec('node excute.js', (error, stdout, stderr) => {
if(error) {
console.log(error.message);
return;
}
console.log(stdout);
})
}
check();
I'm thinking about use setTimeout inside my module file or auto-created JS file. But i really get stuck and confused !!!. Thank every one
It is impossible to deterministically detect an infinite loop within another process. In your case you may simply want to timeout the process:
const {exec} = require("child_process");
async function check(fileName, timeOut = 1000) {
return new Promise((resolve, reject) => {
let _t = null;
// Execute
const process = exec(`node ${fileName}`, (error, stdout, stderr) => {
if (_t) clearTimeout(_t);
if (error) reject(error);
else resolve(stdout);
})
// Time Out
_t = setTimeout(() => {
process.kill(-1);
reject(undefined);
}, timeOut);
})
}
check()
.then(stdout => console.log(stdout))
.catch(console.error);
Pay attention to exec() as it is executing code on your server. If the code contains errors (as in your case) nothing assures you those errors are not fatal for your system. Furthermore never execute untrusted code like that.