javascript - 获取 Nodejs eval 的错误行

标签 javascript node.js

我想知道我是如何在 eval 中遇到行错误的。

例如,

try {
    eval("var hello = 5; hello hello");
} catch(err) {
    console.log(err.line) // should print 2
}

如有任何帮助,我们将不胜感激,谢谢。

最佳答案

如果你在 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))
}

运行此代码将记录错误行:3

这是 vm 包的文档:https://nodejs.org/api/vm.html

关于javascript - 获取 Nodejs eval 的错误行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468091/

相关文章:

javascript - localtunnel 是如何工作的?

ios - 原生 IOS 应用和 node.js

node.js - Azure Linux Web 服务器没有响应我的 Docker 容器

javascript - 为什么 fs.write 中出现 "bad argument"错误

node.js - 无法将Nightmarejs应用程序部署到Heroku

JavaScript 正则表达式 : find GUID in an URL and replace it

javascript - 如何在不使用 foreach 的情况下访问动态更新的 knockout observableArray 的特定元素

javascript - setInterval(function(),time) 在运行时更改时间

javascript - 如何在执行一次后停止javascript中的focus()函数?

javascript - IE 格式化文本区域中的 HTML