node.js - Node.js后端/服务器: Cannot `require` in `new Function` instance

标签 node.js error-handling

我试图在使用require初始化的函数中使用new Function。有没有办法允许字符串中的require语句

// 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));

关于node.js - Node.js后端/服务器: Cannot `require` in `new Function` instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62312780/

相关文章:

json - 在 JSON.NET 数据解析期间忽略解析错误

python - 在类实例化期间干净地处理问题

node.js - 将 mongodb 数据解析为 javascript 数组对象

javascript - 如何修复 'npm run build'后的空白网页

mysql - LINUX MINT mysql

r - R : Create a txt file with the error handling of tryCatch

python - 无法将简单的文本文件转换为 pandas 数据框

javascript - MongoDB 到 Elasticsearch 索引

node.js - 如何在 Node js中将彩色图像(jpg,jpeg,png)更改为黑白或灰度

node.js - WebSocket WS SSL