Skip to content

Instantly share code, notes, and snippets.

@y21
Last active April 6, 2023 07:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save y21/55f4866eb9dea49d52b15edb5c16b026 to your computer and use it in GitHub Desktop.
Save y21/55f4866eb9dea49d52b15edb5c16b026 to your computer and use it in GitHub Desktop.
vm2
const {NodeVM} = require('vm2');
const {isMainThread, Worker, parentPort} = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
let lastMessage = null;
worker.on('message', () => lastMessage = Date.now());
worker.on('online', () => lastMessage = Date.now());
const checker = setInterval(() => {
// Last ping was >5s ago, terminate it
if (lastMessage !== null && Date.now() - lastMessage >= 5000) {
clearInterval(checker);
worker.terminate();
console.log('killed');
}
}, 1000);
} else {
// worker_threads code
const vm = new NodeVM({
require: {
external: ['axios'],
builtin: false
},
sandbox:{
logs:[],
response:'',
},
eval:false,
wasm:false,
});
vm.run(`for(;;);`);
setInterval(() => parentPort.postMessage('ping'), 500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment