Skip to content

Instantly share code, notes, and snippets.

@trongcong
Forked from mikesmullin/trace.js
Created October 24, 2020 08:36
Show Gist options
  • Save trongcong/0771a82c54c4fcee3dcc82c0ac7e9d2d to your computer and use it in GitHub Desktop.
Save trongcong/0771a82c54c4fcee3dcc82c0ac7e9d2d to your computer and use it in GitHub Desktop.
Node.JS print filename and line number prefixed to console log output
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");
@trongcong
Copy link
Author

trongcong commented Oct 24, 2020

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();

https://gist.github.com/mikesmullin/008721d4753d3e0d9a95cda617874736#gistcomment-3254092

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment