首页 > 解决方案 > vm runInNewContext 在使用模块 _compile 时不执行代码

问题描述

我正在使用以下代码在用打字稿编写的节点代码中即时执行字符串

import path from 'path';
import { Module } from 'module';

const getNodeModulesLookupPath = (filename: string) => {
  let dir = path.dirname(filename);
  return (Module as any)._nodeModulePaths(dir);
};

export const runCode = (code: string, fileName: string) => {
  let mod = new Module(fileName, module.parent as any);
  mod.filename = fileName;
  mod.paths = getNodeModulesLookupPath(fileName);
  (mod as any)._compile(code, fileName);
};

如果我执行此代码,我可以看到 console.log

"use strict";
exports.__esModule = true;
var cucumber_1 = require("cucumber");
var And = cucumber_1.When;
// globals for now
var left = 0;
var right = 0;
var result = 0;
cucumber_1.Given('I take the number {int}', function (n) {
    left = Number(n);
});
cucumber_1.When('I take the number {int}', function (n) {
    right = Number(n);
});
And('I add them', function () {
    result = left + right;
});
cucumber_1.Then('I will have {int}', function () {
    console.log("the result is " + result);
});

但是如果我使用vmfrom node and runInNewContext,我看不到 console.log 的输出

import vm from 'vm';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const runCode = (code: string, fileName: string) => {
  console.log(code);
  vm.runInNewContext(code, { exports: {}, module: {}, require: require });
};

标签: node.js

解决方案


如果您想在控制台中查看将由虚拟机处理的代码日志,您应该console以与您传递的方式相同的方式将您的实例传递给虚拟机requiremodule并且exports.

试试这个代码

import vm from 'vm';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const runCode = (code: string, fileName: string) => {
  console.log(code);
  vm.runInNewContext(code, { exports: {}, module: {}, require: require, console: console });
};

推荐阅读