-
-
Save mikesmullin/008721d4753d3e0d9a95cda617874736 to your computer and use it in GitHub Desktop.
const path = require('path'); | |
function trace(s) { | |
const orig = Error.prepareStackTrace; | |
Error.prepareStackTrace = (_, stack) => stack; | |
const err = new Error(); | |
Error.captureStackTrace(err, arguments.callee); | |
Error.prepareStackTrace = orig; | |
const callee = err.stack[0]; | |
process.stdout.write(`${path.relative(process.cwd(), callee.getFileName())}:${callee.getLineNumber()}: ${s}\n`); | |
} | |
module.exports = trace; | |
trace("hey"); |
I am experiencing such error
typeError: callee.getFileName is not a function
any help?
That is Error.prototype.stack[0].getFileName
. It is not well-documented anywhere, and the whole of Error.prototype.stack
is classified as non-standardized by MDN. It works for me, but if its not defined you should question whether you are using latest Node.JS version, and whether the code that generated the Error did it in an unconventional way. It will not work in any browser; this is server-side Javascript only.
see also:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack
https://nodejs.org/api/errors.html#errors_error_stack
https://stackoverflow.com/questions/11386492/accessing-line-number-in-v8-javascript-chrome-node-js
Reversing lines 8 and 9 works for me. Thank you.
I have a workaround without using arguments.callee
, which is now deprecated :
const orig = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => stack;
const err = new Error();
Error.captureStackTrace(err, global);
const callee = err.stack[1];
Error.prepareStackTrace = orig;
const callerFile = path.relative(process.cwd(), callee.getFileName());
const callerLine = callee.getLineNumber();
KasparEtter customized console.log()
thanks in part to ( "Inspired by" quoting him) code in this GitHub, so I think it's relevant to show its solution: https://stackoverflow.com/a/60305881/9391770
I find his solution amazing!
let x = new Error().stack.split("\n")[1];
console.log(x);
lines 8 and 9 are reversed