可以在 node.js 中实现。由于安全原因,在运行脚本时:
node script.js 在 nodejs 提供的 global 对象中看不到函数或变量,但是在使用 node -e "some script" 运行脚本时,可以从 global object 访问函数和变量。
所以我写了 3 个脚本。
- 读取需要解析的文件(scriptThatNeedsToBeParsed.js)和解释文件(interpretFile.js)。组合它们并使用 node -e combinedFileContents 创建一个进程
- 需要解析的脚本
- 用于解释解析文件的脚本
scriptThatNeedsToBeParsed.js:
function A(a,b,c){}
var abc;
function T(){}
readFile.js:
我正在读取需要解析的文件并定义了 2 个变量:
START_FROM_THIS_OBJECT 在文件内容之前,END_TO_THIS_OBJECT 在文件内容之后。所以以后我会知道从哪里到哪里搜索函数和变量。
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);
});
解释文件.js:
我只在上面定义的 2 个控制变量“之间”搜索函数和变量
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;
}
}
来自nodejs的global对象的最后一部分: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,<<<<<<<<<<<<<<<<
我运行脚本:node readFile.js scriptThatNeedsToBeParsed.js interpretFile.js
这是输出:
功能:A 带 nr 参数:3
变量:abc,值为:NaN
函数 :T with nr args: 0