In Node.js, I'm trying to obtain the name of current function being executed:
function doSomething(req, res) {
console.log('Function name: ' + doSomething.name);
}
This works well, but I'd like (if possible) to obtain the name within the current context. This way, if I renamed the method later I don't have change it manually. Is there a generic object (i.e. similar to 'this') that points to the current function being executed/current context? Thank you.
Using __dirname in a Node script will return the path of the folder where the current JavaScript file resides. Using ./ will give you the current working directory. It will return the same result as calling process. cwd() .
To get the name or hostname of the OS, you can use the hostname() method from the os module in Node. js. /* Get hostname of os in Node. js */ // import os module const os = require("os"); // get host name const hostName = os.
A named function has 4 basic parts: the function keyword, the name you give it and use to refer to it, the parameter list, and the body of the function. Named functions can also be assigned to attributes on objects, and then you can call the function on the object: function sayHi() { console.
The call() method returns the result of calling the functionName() . By default, the this inside the function is set to the global object i.e., window in the web browsers and global in Node. js. Note that in the strict mode, the this inside the function is set to undefined instead of the global object.
Short answer: Object.values(this)[0].name
or arguments.callee.name
Long Answer for the 1st option:
let myInstanceArray = Object.values(this)
Enumerates the object properties as an array
let myInstance = myInstanceArray[0]
Gets the first, and only, item in the array
let myName = myInstance.name
Gets the name of the item.
I don't want to repeat the answers in the "possible duplicate" suggestions from Ian, but there is a solution that might be worth mentioning in addition to them:
You could use a named function expression, to have one name, that is accessible from outside of the function and one name that is accessible from inside:
var x = function y() {
console.log(y);
};
console.log(x);
Now, if you decide to give your function a different name, you can just change x
while still be able to refer to the function by using y
.
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