Created
February 28, 2019 18:06
-
-
Save maiha/3cb359685d65314d5d95321da669339f to your computer and use it in GitHub Desktop.
Javascript AST: print CallExpression or FunctionDeclaration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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