Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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 logging events. I haven't found anything similar to it in the node.js world.

Does anyone have suggestions or know how I can get line number and file name in node.js for logging purposes?

I'm looking for something like:

console.log(__FILE__ + "." + __LINE__ + "\t" + new Date().toISOString() + " Message ");
like image 315
jeremy Avatar asked Nov 27 '12 19:11

jeremy


People also ask

What does node JS contain?

As Wikipedia states: “Node. js is a packaged compilation of Google's V8 JavaScript engine, the libuv platform abstraction layer, and a core library, which is itself primarily written in JavaScript.” Beyond that, it's worth noting that Ryan Dahl, the creator of Node.

Does Nodejs use C?

Yes, Node. js has a great portion of it written in C/C++ and a lot of its modules are actually implemented in C/C++. Just like any other javascript project out there, Node. js internally has a collection of dependencies that it uses to actually execute your code.

What is the main file in node JS?

We have chosen main. js to be the main file. With the npm install builtin-modules we install the builtin-modules module locally. A new node_modules directory is created where the modules and their dependencies are stored.

CAN node js write to file?

Writing to a file is another of the basic programming tasks that one usually needs to know about - luckily, this task is very simple in Node. js. We can use the handy writeFile method inside the standard library's fs module, which can save all sorts of time and trouble.


1 Answers

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.

like image 156
travis Avatar answered Sep 20 '22 08:09

travis