Does node.js have anything like __file__ and __line__ like the c++ preprocessor macros?

后端 未结 4 693
日久生厌
日久生厌 2021-01-11 15:35

I\'m working on enhancing logging in some node.js applications. In the past have used C++\'s __ file__ and __ line __ preprocessor macros to help us track down issues when

相关标签:
4条回答
  • 2021-01-11 16:19

    see the global object:

    __filename 
    

    for the lineNumber see this post: javascript node.js getting line number in try catch?

    0 讨论(0)
  • 2021-01-11 16:20

    See: Accessing line number in V8 JavaScript (Chrome & Node.js)

    Then for a filename:

    Object.defineProperty(global, '__file', {
      get: function(){
        return __stack[1].getFileName().split('/').slice(-1)[0];
      }
    });
    

    You could also just use the process.argv[1] instead of calling the __stack getter but I wanted to keep it similar.

    0 讨论(0)
  • 2021-01-11 16:24

    Expanded on the previous answers a bit into here: https://gist.github.com/gavinengel/8572856

    Allows setting globals: __line, __file, __ext, __dir

    By the way, how do I create?: __function, __method, __class

    0 讨论(0)
  • 2021-01-11 16:28

    Just use the C preprocesor, adds an extra build step to your code but then it allows stripping out your logging for production code.

    0 讨论(0)
提交回复
热议问题