Skip to content

Instantly share code, notes, and snippets.

@maiha
Created February 28, 2019 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maiha/3cb359685d65314d5d95321da669339f to your computer and use it in GitHub Desktop.
Save maiha/3cb359685d65314d5d95321da669339f to your computer and use it in GitHub Desktop.
Javascript AST: print CallExpression or FunctionDeclaration
/* npm install acorn acorn-walk */
/* usage: nodejs print-func.js foo.js --call */
let mode = 'name';
let index = process.argv.findIndex(function(e) { return e == "--call"});
if (index > 0) { process.argv.splice(index, 1); mode = 'call'; }
let filename = process.argv[2];
if (!filename) throw "file not found";
const acorn = require("acorn")
const walk = require("acorn-walk")
const glob = require("glob")
const path = require("path")
const fs = require("fs")
glob.sync("./prelude/*.js").forEach( function( file ) {
require( path.resolve( file ) );
});
fs.readFile(filename, "utf8", (error, code) => {
if (error) throw error;
var ast = acorn.parse(code, {ecmaVersion: 8});
walk.simple(ast, {
CallExpression(node) {
if (mode == 'call') {
var name = node.callee.name;
if (name) console.log(name); // skip 'undefined'
}
},
FunctionDeclaration(node) {
if (mode == 'name') {
console.log(node.id.name)
}
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment