获取 nodejs 函数定义

Eva*_*van 2 javascript node.js

我想从 js 文件中收集已定义函数的源代码。这些函数可能很复杂,并且有许多左括号和右括号,因此使用正则表达式会很困难。我只需要稍后在代码中可调用的函数,如下所示

function dump_vars() {
    Object.keys(global).forEach(function (key) {
        console.log(key);
        console.log(global[key]);
    });
}
Run Code Online (Sandbox Code Playgroud)

有没有办法从 node.js 中获取函数定义?它们可能保存在全局对象之类的地方吗?

Pau*_*gel 5

如果您有权访问函数对象,则可以使用该.toString()方法获取其定义。根据Mozilla 的文档

即 toString 对函数进行反编译,返回的字符串包括函数关键字、参数列表、花括号和函数体的来源。

例如,假设您在 中定义了一个模块mymodule.js

function add (a, b) {
    return a + b;
};

function mul (a, b) {
    return a * b;
};

module.exports = {
    a: add,
    b: mul
};
Run Code Online (Sandbox Code Playgroud)

然后,在index.js

var mymodule = require('./mymodule.js')

Object.keys(mymodule).forEach(function (fun) {
    console.log(mymodule[fun].toString());
})
Run Code Online (Sandbox Code Playgroud)

这将输出:

$ node index.js
function add(a, b) {
    return a + b;
}
function mul(a, b) {
    return a * b;
}
Run Code Online (Sandbox Code Playgroud)

编辑:例如,这是 AngularJS 实现依赖注入的方式,通过使用.toString()来获取函数代码以了解函数参数的名称。请参阅此相关 SO 答案