英文:
How to know when a vm script finishes execution?
问题
以下是已翻译的代码部分:
const vm = require('vm');
// 将 setTimeout 函数传递给沙盒
const sandbox = { setTimeout };
// 在 2 秒后将 'stackoverflow' 赋给全局变量 `test`
const rawCode = 'setTimeout(() => { test = "stackoverflow"; }, 2000);';
const script = new vm.Script(rawCode);
script.runInNewContext(sandbox);
// 输出: {
// setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] }
// }
console.log(sandbox);
// 输出: {
// setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] },
// test: 'stackoverflow'
// }
setTimeout(() => console.log(sandbox), 2000);
对于您的最后一个问题,有没有一种方法可以确定 vm 上下文中的代码是否已完全执行,且事件循环中没有剩余的回调函数?
英文:
Here is a sample code:
const vm = require('vm');
// Pass setTimeout function to the sandbox
const sandbox = { setTimeout };
// Will assign 'stackoverflow' to global variable `test` after 2 seconds
const rawCode = 'setTimeout(() => { test = "stackoverflow"; }, 2000);';
const script = new vm.Script(rawCode);
script.runInNewContext(sandbox);
// Output: {
// setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] }
// }
console.log(sandbox);
// Output: {
// setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] },
// test: 'stackoverflow'
// }
setTimeout(() => console.log(sandbox), 2000);
Is there any way to tell that the code in the vm's context is fully executed and there are no callbacks left in its event loop?
答案1
得分: 0
根据这个在Github上的评论(由bnoordhuis编写):
> 上下文共享事件循环。
因此,如果我们在VM代码中调用setTimeout
,回调将在与“父级”相同的队列中注册。之后无法判断回调属于VM代码还是属于父级。因此,我们无法跟踪在VM中注册的回调数量,也无法确定何时完成运行。
我已在Node.js项目上创建了一个功能请求,但显然存在重大挑战需要克服。
英文:
According to this comment on Github (written by bnoordhuis):
> Contexts share the event loop.
So if we call setTimeout
in VM code, the callback is registered in the same queue with the "parent". There is no way to tell if the callback belongs to VM code or to the parent after that. Therefore we cannot track the number of registered callbacks in VM and cannot tell when it finishes running.
I have created a feature request on Node.js project but apparently there are significant challenges to overcome.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论