node.js - Node.js 后端/服务器:在“新函数”实例中无法“要求”
问题描述
我正在尝试在require
使用new Function
. 有没有办法允许字符串中的要求语句
// test.js
let fnString = `
const os = require("os");
return os.platform();
`;
const fn = new Function(fnString);
console.log(fn());
运行文件test.js
:
$ node test.js
undefined:4
const os = require("os");
^
ReferenceError: require is not defined
at eval (eval at <anonymous> ({path}/test.js:8:12), <anonymous>:4:12)
at Object.<anonymous> ({path}/test.js:9:13)
成功地让它与node
REPL 一起工作:
$ node
Welcome to Node.js v14.4.0.
Type ".help" for more information.
> f = new Function(`
const os = require("os");
return os.platform();
`);
> f()
'linux'
>
解决方案
您可以将require
作为参数添加到函数并将其传递给函数,如下所示:
let fnString = `
const os = require("os");
return os.platform();
`;
const fn = new Function('require', fnString);
console.log(fn(require));
推荐阅读
- powershell - 如何读取 .xls 文件并根据 .xls 中输入的值创建 .xml?
- c# - C# SQL Server 数据库更新数据
- javascript - 如何使用 puppeteer 按下 Audio Controls 元素的播放按钮
- c++ - 将 std::array 移动到另一个 std::array
- java - 如何在邮递员中将多个字符串包装成单个字符串以调用 Spring Boot Rest API 获取请求
- javascript - 打开 FCM 通知时如何采取行动/移动屏幕?
- javascript - 翻牌类未在 javascript 中转换
- csv - LiteDB 导入一个 csv
- python - `numpy.nanpercentile` 非常慢
- java - 如何从 JSONObject 获取文件或流?