首页 > 解决方案 > 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)

成功地让它与nodeREPL 一起工作:

$ 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'

>

标签: node.jserror-handling

解决方案


您可以将require作为参数添加到函数并将其传递给函数,如下所示:

let fnString = `
const os = require("os");
return os.platform();
`;

const fn = new Function('require', fnString);
console.log(fn(require));

推荐阅读