Home > Software design >  How locate the row where the output statement resides in nodejs
How locate the row where the output statement resides in nodejs

Time:11-21

As we all know, we can easy to see the line of an output statement in the browser, just like follow picture

enter image description here

but in the nodejs env, how do I know what line is 'output statement' in.


I have this need because I want to know better during development where the information is coming from when the program fails. Of course, I could have each output statement carry a unique character, like console.log('1', '...'), console.log('2', '...') but that feels silly and unhackable to me.

I'll show you a simple piece of code as an illustration

try {
  throw new Error('something error')
} catch (error) {
  console.log(error.stack)
}

Run the above code I can see the output:

Error: something error
    at file:///c:/Users/Linhieng/Desktop/tmp/a.js:2:9
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)

the above output tell us what line is the error in, but I want to know the line of console.log.

CodePudding user response:

I thing woth simple logging the only solution here is a manually passing the according line number. Something like that:

console.log(error, LINE_NUMBER);

Another possible solution probably could be when you use some kind of a external configurable NodeJS debugger software. There probably will be provided a functionality related you your needs.

CodePudding user response:

You can monkeypatch console.log with code that parses the stack string, since this is Node.js and the format only varies across releases (unlike on browsers, where it can vary by browser as well):

const realLog = console.log;
console.log = (...msgs) => {
    try {
        throw new Error("something error");
    } catch (error) {
        const lines = error.stack.split(/(?:\r\n|\r|\n) /);
        msgs.push(`[${lines[2].trim()}]`);
    }
    realLog(...msgs);
};

Then for instance, this:

function example() {
    console.log("Hi there");
}

example();

shows

Hi there [at example (file:///____/temp.js:13:13)]

At present, the "parsing" is really easy — just split on newlines and take the third element of the array. But you might want to extract more information, or the format could change in future versions to require more complicated "parsing."

  • Related