node.js - 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);
});
但是如果我使用vm
from 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 });
};
解决方案
如果您想在控制台中查看将由虚拟机处理的代码日志,您应该console
以与您传递的方式相同的方式将您的实例传递给虚拟机require
,module
并且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 });
};
推荐阅读
- html - 使 Bootstrap Nav 置顶
- azure-sql-database - OutputDataConversionError.TypeConversionError 使用来自 IoT 中心的流分析写入 Azure SQL DB
- wolfram-mathematica - 如何使用 sympy 或 MMA 将指数函数替换为复杂表达式中的系列?
- c# - 将 null 设置为文档属性并在更新时从数据库中删除字段
- nativescript - Nativescript - 图表未显示
- android - 在qt-android中使用pocketsphinx,使用中文包时出现问题
- c# - 第一个匹配路由必须同时指定控制器和操作?
- laravel - _time 后缀对 laravel 数据库设计有什么用?
- http-headers - 如何使用 Keycloak Gatekeeper 设置自定义标头?
- javascript - Array.from({length: 5}) 和 Array(5).fill(undefined) 有什么区别?