你如何导入一个可能有语法错误的模块?

How do you import a module that may have syntax errors in it?

我有两个脚本 a.jsb.jsb.js 可能有语法错误。我该如何解释?

a.js

let codeForRunning = require('b.js');

try {
    resultOfCode = codeForRunning.func(TEST);
}
catch (err) {
    resultOfCode = err
}

b.js

function myFunction (argument) {
    return 'Hello world
}

module.exports = { func: saveWrittenCode }

您可以在 try / catch 块中要求模块:

try {
    const b = require('./b');
    // Code
} catch (err) {
   console.log('Module b could not be loaded');
}

另一种方法是将模块作为文本加载并在运行时进行评估:

const fs = require('fs');

const b = fs.readFileSync('./b.js', 'utf8');

try {
    const evaluated = eval(b);
    // Code
} catch (err) {
   console.log('Module b could not be loaded');
}

Obs:确保您要评估的代码是值得信赖的,否则您将容易受到远程代码执行的攻击