如何知道虚拟机脚本执行完毕?

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年1月6日 20:30:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定