Return all of the functions that are defined in a Javascript file

前端 未结 4 1902
孤独总比滥情好
孤独总比滥情好 2020-11-27 19:53

For the following script, how can I write a function that returns all of the script\'s functions as an array? I\'d like to return an array of the functions defined in the sc

4条回答
  •  盖世英雄少女心
    2020-11-27 20:29

    More than 1 hour wasted on this.

    This is read .js file from node.js

    1.Install a node module:

    npm i esprima
    

    2.Assume you have a function func1 declared like below, in a file a.js in current directory:

    var func1 = function (str1, str2) {
        //
    };
    

    3.And you would like to get name of it, that is func1, the code is below:

    const fs = require("fs");
    const esprima = require("esprima");
    
    let file = fs.readFileSync("./a.js", "utf8");
    
    let tree = esprima.parseScript(file);
    tree.body.forEach((el) => {
        if (el.type == "VariableDeclaration") {
            // console.log(el);
            console.log(el.declarations);
            console.log(el.declarations[0].id);
            console.log(el.declarations[0].id.name);
        }
    });
    

    4.You can also get other details like parameters str1, str2, etc, uncomment the console.log(el) line to see other details.

    5.You can put both above code parts in one file, to get the details of current file (a.js).

提交回复
热议问题