1

Suppose I have:

var err = new Error('My error!');

How to get line and file name, where Error was created? Like in PHP:

$ex = new \Exception();
$ex->getLine();
$ex->getFile();   
1
  • err.stack can give you the stack trace. Commented May 26, 2017 at 11:36

2 Answers 2

3

You can use stack-trace node module. This gives module name and line number

Sign up to request clarification or add additional context in comments.

Comments

1

To get the file name for the current file: use __filename.

To get the folder for the current file: use __dirname

To parse the file from an Error object, you need an Error with a stack property, that hopefully points to files. You would need then to parse the filename and line from the stack string or use a module that does so.

> new Error().stack
Error
    at repl:1:1
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:346:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:545:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.