我想知道我是如何在eval中获得线路错误的。
例如,
try {
eval("var hello = 5; hello hello");
} catch(err) {
console.log(err.line) // should print 2
}
任何帮助都将不胜感激,谢谢。
答案 0 :(得分:1)
如果您在Node中,我宁愿使用vm软件包,因为它更安全。 这是一个有效的解决方案
const vm = require('vm');
// this is the sandbox, it gives the scrip only access to these vars, which
makes it safer than a pure eval;
const sandbox = {
count: 2
};
try {
// create script to be ran
// I use backtick for new lines
const script = new vm.Script(
`count += 1;
throw new Error('test');`
);
// create the context from the sandbox
const context = new vm.createContext(sandbox);
// run the script
script.runInContext(context, {
lineOffset: 0,
displayErrors: true,
});
} catch(e) {
console.log('Line of error :', e.stack.split('evalmachine.<anonymous>:')[1].substring(0, 1))
}
运行此代码将记录Line of error: 3
。
以下是vm包的文档:https://nodejs.org/api/vm.html