NodeJS `isolated-vm`:如何引用isolate内部的函数

问题描述 投票:0回答:1

以下代码:

const ivm = require('isolated-vm');

const isolate = new ivm.Isolate();
const context = isolate.createContextSync();

context.setSync('log', new ivm.Callback(x => console.log(x)));
// receives a function and triggers it on an interval
context.setSync('onEvent', new ivm.Callback((handler) => {
   setInterval(() => handler(), 1000)
}));

const script = isolate.compileScriptSync(`onEvent(() => log('hello'))`);
script.runSync(context);

产生以下错误:

function '() => log('hello')' could not be cloned

我理解为什么一个函数不能从一个隔离复制到另一个隔离,但我想找回对该回调的引用,以便稍后可以使用

ref.apply(..)
触发它。

如何从隔离内部获取对函数的引用?

(不将

ivm
模块本身暴露于不安全的隔离物中)

node.js npm reference v8 isolate
1个回答
0
投票

我用

context.evalClosureSync(`
  globalThis.console = {
    log: $0
  }
`,
[
   (...args) => console.log(...args)
]);

这段代码可以解决您的问题吗?

© www.soinside.com 2019 - 2024. All rights reserved.