Billy Moon
Billy Moon

Reputation: 58601

Delete javascript function at position in file

I would like to delete a function form javascript at a position in a js source file, and re-write the file without it, so...

I have used a code analysis tool to get the position of the target function for deletion as line 5, column 0, in myfile.js

1 function keepme(x) {
2   return x + ' is ok';
3 }
4 
5 function delme(y) {
6   return y + ' oh why';
7 }
8 
9 /* code continues here */

I want to now use some kind of parser I guess in order to remove the function delme from the file.

I have looked at UglifyJS's build in parser, and treewalker, but seems to report the position of function delme(y), not the whole function, so can't figure out how to find end point of function definition.


 For posterity...

var recast = require("recast");
var fs = require("fs");
var code = fs.readFileSync("billymoon.js").toString();

function stripByPosition(code, line, col) {
  
  var ast = recast.parse(code);

    recast.visit(ast, {
        visitFunctionDeclaration: function(path) {
            if (path.node.loc.start.line === line && path.node.loc.start.column === col) {
                path.prune();
            }
            return false;
        }
    });

  return recast.print(ast).code;

}

console.log(stripByPosition(code, 5, 0));
console.log(stripByPosition(code, 1, 0));

Upvotes: 2

Views: 365

Answers (1)

Luka Žitnik
Luka Žitnik

Reputation: 1168

Maybe you would like to use the recast tool for this. Here's an example.

var recast = require("recast");
var fs = require("fs");
var code = fs.readFileSync("billymoon.js").toString();
var ast = recast.parse(code);

recast.visit(ast, {
  visitFunctionDeclaration: function (path) {
    var start = path.node.loc.start;
    if (start.line === 5 && start.column === 0) {
      path.prune();
    }
    return false;
  }
});

console.log(recast.print(ast).code);

Upvotes: 3

Related Questions