Search code examples
javascriptuglifyjs

Extract private function from javascript using parser


I am trying to use a parser (via uglify-js, but any other is fine too) in order to extract private function from input string.

contents of a.js

var UglifyJS = require('uglify-js');
var ast = UglifyJS.parse(require('fs').readFileSync('b.js').toString());

var stream = UglifyJS.OutputStream({});

// need to manipulate ast here to extract the `sum` function
ast.print(stream)
console.log(stream+'')

contents of b.js

var addRandom = (function() {
    function sum(x, y) {
        return x + y
    };

    return function (input) {
        return sum(input, Math.random());
    };
})();

running node a.js yields...

var fn=function(){function sum(x,y){return x+y}function addRandom(input){return sum(input,Math.random())}return{addRandom:addRandom}}();

... but I need to manipulate the ast before being output, to extract the sum function. What I want to print out is...

function sum(x,y){return x+y}

How can I extract the part of the AST tree I want before output?


Solution

  • var UglifyJS = require('uglify-js');
    var code = require('fs').readFileSync('b.js').toString();
    var stream = UglifyJS.OutputStream({});
    var toplevel = UglifyJS.parse(code);
    var walker = new UglifyJS.TreeWalker(function(node){
        if (node instanceof UglifyJS.AST_Defun) {
            node.print(stream);
        }
    });
    
    toplevel.walk(walker);
    console.log(stream + '');