首页 > 代码库 > NodeJs获取函数名称和函数操作整理

NodeJs获取函数名称和函数操作整理

var aa = function () {
    log("xxxx");
};
aa();

var model = {};
model.test = function () {
    log("model.test");
};
model.test();

function log(msg) {
    var info = stackInfo();
    var method = info[‘method‘];
    var file = info[‘file‘];
    var line = info[‘line‘];
    console.log("(" + method + ") <" + file + ":" + line + "> " + msg);
}

// 这里是主要方法
function stackInfo() { var path = require(‘path‘); var stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/i; var stackReg2 = /at\s+()(.*):(\d*):(\d*)/i; var stacklist = (new Error()).stack.split(‘\n‘).slice(3); var s = stacklist[0]; var sp = stackReg.exec(s) || stackReg2.exec(s); var data =http://www.mamicode.com/ {}; if (sp && sp.length === 5) { data.method = sp[1]; data.path = sp[2]; data.line = sp[3]; data.pos = sp[4]; data.file = path.basename(data.path); } return data; }

输出格式内容:

(aa) <c.js:6> xxxx
(Object.model.test) <c.js:12> model.test

NodeJs获取函数名称和函数操作整理