It is possible to do it in node.js. Because of security reasons while runing a script with:
node script.js one can not see functions or variables in global object provided by nodejs but while running a script with node -e "some script" one has access to functions and variables from global object.
So I wrote 3 scripts.
- Reads the file that needs to be parsed (scriptThatNeedsToBeParsed.js) and the interpret file (interpretFile.js). Combines them and creates a process with node -e combinedFileContents
- Script that needs to be parsed
- Script used to interpret parsed file
scriptThatNeedsToBeParsed.js:
function A(a,b,c){}
var abc;
function T(){}
readFile.js:
I am reading the file that needs to be parsed and I define 2 variables:
START_FROM_THIS_OBJECT before the content of the file and END_TO_THIS_OBJECT after the content of the file. So later I would know from where to where to search functions and variables.
if(process.argv.length !=4 )
{
console.log("Usage %s <input-file> <interpret-file>",process.argv[0]);
process.exit(0);
}
var input_file = process.argv[2];
var interpret_file = process.argv[3];
var fs = require('fs');
var fileToParse = ";var START_FROM_THIS_OBJECT;";
fileToParse += fs.readFileSync(input_file, "utf8");
var interpretFile = fs.readFileSync(interpret_file, "utf8");
fileToParse += ";var END_TO_THIS_OBJECT;";
var script = fileToParse + interpretFile;
var child = require('child_process').execFile('node',
[
'-e', script,
], function(err, stdout, stderr) {
console.log(stdout);
});
interpretFile.js:
I search for functions and variables just "between" the 2 control variables defined above
var printObjects = false;
for(var item in global)
{
if(item == "END_TO_THIS_OBJECT")
{
printObjects = false;
}
if(printObjects)
{
if(typeof(global[item]) == "function")
{
console.log("Function :%s with nr args: %d",item,global[item].length);
}
else
{
console.log("Variable :%s with value: %d",item,global[item]);
}
}
if(item == "START_FROM_THIS_OBJECT")
{
printObjects = true;
}
}
The last part of the global object from nodejs: console.log(global);
module:
{ id: '[eval]',
exports: {},
parent: undefined,
filename: 'E:\\LOCAL\\xampp\\htdocs\\nodejs\\[eval]',
loaded: false,
children: [],
paths:
[ 'E:\\LOCAL\\xampp\\htdocs\\nodejs\\node_modules',
'E:\\LOCAL\\xampp\\htdocs\\node_modules',
'E:\\LOCAL\\xampp\\node_modules',
'E:\\LOCAL\\node_modules',
'E:\\node_modules' ] },
__dirname: '.',
require:
{ [Function: require]
resolve: [Function],
main: undefined,
extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
registerExtension: [Function],
cache: {} },
START_FROM_THIS_OBJECT: undefined,<<<<<<<<<<<<<<
A: [Function: A],
abc: undefined,
T: [Function: T],
END_TO_THIS_OBJECT: undefined,<<<<<<<<<<<<<<<<
I run the script with : node readFile.js scriptThatNeedsToBeParsed.js interpretFile.js
This is the output:
Function :A with nr args: 3
Variable :abc with value: NaN
Function :T with nr args: 0