Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the function and their arguments from a js file? javascript

There is a test.js:

const add = (x,y) => {
    return x+y;
}

const multiply = (x,y,z) => {
    return x*y*z;
}

I want to read this test.js from an index.js and print all its function name and arguments;

const fs = require("fs");

let file = fs.readFileSync("./test.js", "utf8");

let functionArg = "Do some operations"

console.log(functionArg)

//Result:
//  add : [x,y]
//  multiply : [x,y,z]

Without module.exports.
Is it possible to read js file and return all its function and their arguments.

like image 434
Shubham Chadokar Avatar asked Nov 06 '22 19:11

Shubham Chadokar


1 Answers

You can get functions and their arguments with the help of a JavaScript parser like esprima.

const fs = require("fs");
const esprima = require('esprima');

let file = fs.readFileSync("./test.js", "utf8");

let functionArg = esprima.parseScript(file);

functionArg.body.forEach(el => {
  let variableDeclarator = el.declarations[0]
  let params = []
  variableDeclarator.init.params.forEach(arg => {
    params.push(arg.name)
  })
  console.log(variableDeclarator.id.name, ' : ', [params.join()])
})

//Result:
// add  :  [ 'x,y' ]
// multiply  :  [ 'x,y,z' ]
like image 141
TGrif Avatar answered Nov 14 '22 23:11

TGrif