0

I would like to put a console.log that would inform the line where it is on. For example: console.log ('Line:', [code to get the line]) The result in the console -> Line: [line number] so I would know where this console.log would have been written on the code.

There is a simple code that returns this number line in js?

Thx

FireEagle
  • 21
  • 4

1 Answers1

1

You can throw an error (since it contains a stack-trace back to where the error was thrown) and parse it's string representation:

const getLineNumber = () => {
  const getErrorObject = () => {
      try { throw Error('') } catch(err) { return err; }
  }

  const err = getErrorObject();
  const callerLine = err.stack.split("\n").pop();
  return callerLine.slice(callerLine.indexOf("at ")+3, callerLine.length);
}

// The line numbers are wrong inside the inline code snippet runner
// This is because SO adds some wrapper code to each snippet
console.log('Line:', getLineNumber());
console.log('Line:', getLineNumber());
console.log('Line:', getLineNumber());
console.log('Line:', getLineNumber());
Olian04
  • 6,480
  • 2
  • 27
  • 54