Get nodejs function definitions

javascript, node.js

Solution

If you have access to the function object, then you can get its definition using the `.toString()` method. Per Mozilla's documentation:

That is, toString decompiles the function, and the string returned includes the function keyword, the argument list, curly braces, and the source of the function body.

For instance, suppose you define a module in `mymodule.js`:

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

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

module.exports = {
    a: add,
    b: mul
};

Then, in `index.js`:

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

Object.keys(mymodule).forEach(function (fun) {
    console.log(mymodule[fun].toString());
})

This will output:

$ node index.js
function add(a, b) {
    return a + b;
}
function mul(a, b) {
    return a * b;
}

Edit: For instance, this is how AngularJS implements dependency injection, by using `.toString()` to get back the function code to know the name of the function's arguments. See this relevant SO answer.

Problem

I want to gather the source code of defined functions from a js file. The functions can be complex and have many opening and closing brackets so using regex will be hard. I only need functions that are callable later on in the code, like the following ``` function dump_vars() { Object.keys(global).forEach(function (key) { console.log(key); console.log(global[key]); }); } ``` Is there a way to get the function definitions from within node.js? Are they maybe saved somewhere like the global object?

Original source

Related problems