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.
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' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With