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 ");
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With