function main() { let a = fun('hello world') console.log(a) }
function fun(a) { return a }
main()
方法
console.trace
使用如下
1 2 3 4 5 6 7 8 9 10 11
function main() { let a = fun('hello world') console.log(a) }
function fun(a) { console.trace('fun') return a }
main()
输出结果为
1 2 3 4 5 6 7 8 9 10
Trace: fun at fun (c:\Users\zeyu\Desktop\demo\main.js:7:11) at main (c:\Users\zeyu\Desktop\demo\main.js:2:11) at Object.<anonymous> (c:\Users\zeyu\Desktop\demo\main.js:11:1) at Module._compile (node:internal/modules/cjs/loader:1095:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10) at Module.load (node:internal/modules/cjs/loader:975:32) at Function.Module._load (node:internal/modules/cjs/loader:816:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12) at node:internal/main/run_main_module:17:47 hello world
function main() { let a = fun('hello world') console.log(a) }
function fun(a) { printStack() return a }
function printStack() { let stack = new Error().stack console.log(stack) }
main()
输出的结果为一串字符串,如下
1 2 3 4 5 6 7 8 9 10 11
Error at printStack (c:\Users\zeyu\Desktop\demo\main.js:12:16) at fun (c:\Users\zeyu\Desktop\demo\main.js:7:3) at main (c:\Users\zeyu\Desktop\demo\main.js:2:11) at Object.<anonymous> (c:\Users\zeyu\Desktop\demo\main.js:16:1) at Module._compile (node:internal/modules/cjs/loader:1095:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10) at Module.load (node:internal/modules/cjs/loader:975:32) at Function.Module._load (node:internal/modules/cjs/loader:816:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12) at node:internal/main/run_main_module:17:47 hello world
function main() { let a = fun('hello world') console.log(a) }
function fun(a) { printStack() return a }
main()
function printStack() { const callstack = new Error().stack.split('\n') callstack.forEach((s) => { let matchArray = s.match(/at (.+?) \((.+?)\)/) if (!matchArray) return
let name = matchArray[1] let location = matchArray[2] console.log(name, location) }) }
输出结果如下(由于是 Node 环境,所以会输出一些有关模块 modules 的东西)
1 2 3 4 5 6 7 8 9 10
printStack c:\Users\zeyu\Desktop\demo\main.js:14:21 fun c:\Users\zeyu\Desktop\demo\main.js:7:3 main c:\Users\zeyu\Desktop\demo\main.js:2:11 Object.<anonymous> c:\Users\zeyu\Desktop\demo\main.js:11:1 Module._compile node:internal/modules/cjs/loader:1095:14 Object.Module._extensions..js node:internal/modules/cjs/loader:1124:10 Module.load node:internal/modules/cjs/loader:975:32 Function.Module._load node:internal/modules/cjs/loader:816:12 Function.executeUserEntryPoint [as runMain] node:internal/modules/run_main:79:12 hello world
Error.captureStackTrace
Error 中有一个静态方法,同样用于获取调用栈。演示代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
function main() { let a = fun('hello world') console.log(a) }
function fun(a) { let stack = stackTrace() console.log(stack)