Skip to content

Instantly share code, notes, and snippets.

@maiha maiha/print-func.js
Created Feb 28, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.