如何列出节点js脚本中的所有函数?

时间:2012-05-05 19:52:01

标签: javascript node.js reflection

我试过看global,但它只包含变量,而不是函数。如何列出我脚本中创建的所有函数?

5 个答案:

答案 0 :(得分:5)

使用您要查看的文件从命令行运行节点调试。然后你可以使用list(这里有一些大数字)

node debug mini_file_server.js 
< debugger listening on port 5858
connecting... ok
debug> scripts
  26: mini_file_server.js
debug> list(1000)
  1 var http = require('http'),
  2     util = require('util'),
  3     fs   = require('fs');
  4 
  5 server = http.createServer(function(req, res){  
  6     var stream  = fs.createReadStream('one.html'),
  7         stream2 = fs.createReadStream('two.html');
  8     console.log(stream);
  9     console.log(stream2);
 10     stream.on('end', function(){
 11         stream2.pipe(res, { end:false});
 12     });
 13 
 14     stream2.on('end', function(){
 15         res.end("Thats all!");
 16     });
 17 
 18     res.writeHead(200, {'Content-Type' : 'text/plain'});
 19     stream.pipe(res, { end:false});
 20     stream2.pipe(res, { end:true});
 21 
 22 }).listen(8001);
 23 });
debug> 

答案 1 :(得分:3)

如果该函数有一个名称,它将显示在全局中就好了:

mb-work-laptop:~ markbessey$ node
> for (var k in global) { console.log(k); }
global
process
GLOBAL
root
Buffer
setTimeout
setInterval
clearTimeout
clearInterval
console
module
require
k
> function z(a) { return a*10; }
> for (var k in global) { console.log(k); }
global
process
GLOBAL
root
Buffer
setTimeout
setInterval
clearTimeout
clearInterval
console
module
require
k
z
> 
> global.z
[Function: z]

答案 2 :(得分:3)

如果没有像调试器这样的更高级的反射工具,这在节点中是不可能的。

执行此操作的唯一方法是使用因安全问题和其他原因而被删除的__parent__。就像Mark Bessey所说,当你运行脚本时,那些变量就变成了模块闭包变量。如果没有明确导出它们,您就无法在其他地方访问它们。

这不是一个错误,它是设计的。这就是节点的工作原理。但是,如果您只是要求您的用户编写函数表达式赋值,那么一切都可以正常工作:

module.exports = {
    a:function(){
        //same logic you had in the function declaration
    }
}

然后,您可以轻松地反思并枚举module.exports并获取所有函数名称。

答案 3 :(得分:0)

答案 4 :(得分:0)

如果你想做一些AOP,路线是AST。

您可以使用以下内容构建自己的AOP框架:http://esprima.org

或者你可以尝试node-burrito,非常适合不那么复杂的方面:

var burrito = require('burrito');

var src = burrito('someCall()', function (node) {
    if (node.name === 'call') node.wrap('qqq(%s)');
});

将生成

qqq(somecall())