Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining the name of the current function being executed in Node.js

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.

like image 618
titusmagnus Avatar asked Aug 09 '13 18:08

titusmagnus


People also ask

How do I get the current execution server in node JS?

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() .

How do I get the current hostname in node JS?

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.

What is the name of function?

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.

How do you call a function in node JS?

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.


2 Answers

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.

like image 120
Cleber Machado Avatar answered Sep 18 '22 05:09

Cleber Machado


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.

like image 40
basilikum Avatar answered Sep 20 '22 05:09

basilikum