简体   繁体   中英

how to console.log the number of the line in the code

how to console.log the line number of the called function or console.log()

for example in the IDE i can see the line like this. how can I show that by console.log it

14 
15 // other code/logic
16
17 console.error(`error at line ${herePutTheLogic}`);
18

output: error at line 17

在此处输入图像描述

You can use (new Error()).stack to get the stack trace at the current line. it would require some additional parsing to get the line number however.

eg, console.log((new Error()).stack.split(':')[1]) will get it assuming it is at the root of the file, but once you start adding it to functions you'd need something a little more sophisticated.

 console.log( "❌ the error is on the line N." + new Error().stack.split(":")[3] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM