admin管理员组

文章数量:1204007

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.

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.

Share Improve this question asked Aug 9, 2013 at 18:14 titusmagnustitusmagnus 2,0823 gold badges24 silver badges23 bronze badges 7
  • possible duplicate of Javascript get Function Name? – Ian Commented Aug 9, 2013 at 18:15
  • or stackoverflow.com/questions/1013239/… – Ian Commented Aug 9, 2013 at 18:16
  • I don't think is a dupe. Seems that all examples require the actual function (in this case, I'd rather use 'doSomething.name'). The other answer doesn't work because 'arguments.callee' is not allowed under strict mode. – titusmagnus Commented Aug 9, 2013 at 18:28
  • It's not allowed in strict mode because it's deprecated and it's an unusual request to need the function's name; there's rarely a good use case for it. Can you explain your reason for getting the name? – Ian Commented Aug 9, 2013 at 18:32
  • 8 Sure: logging and profiling the app. – titusmagnus Commented Aug 11, 2013 at 5:00
 |  Show 2 more comments

4 Answers 4

Reset to default 6

Short answer: Object.values(this)[0].name

Long Answer:

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.

You can use property name as:

const yourFunction = () => {};

console.log(yourFunction.name);
// output: "yourFunction"

MDN reference

This is a use case for finding error specific information about a function or method. The function name is gotten from error stack info. The printError method will return the function name, where the function is used, where the error occured and where the function is implemented with the error message.

// You can try this out

const extractFunctionName = (stackLine) => {
  const regex = /at (.*?) \(/;
  const match = stackLine.match(regex);
  return match ? match[1] : 'unknown';
}

const printError = (e) => {
   const regex = /\((.*):(\d+):(\d+)\)$/
   const caller = regex.exec(e?.stack.split("\n")[2]);
   const issue = regex.exec(e?.stack.split("\n")[1]);

   let formattedErr = {
      functionName: extractFunctionName(issue["input"]),
      calledIn: caller[1],
      calledAt: `${caller[2]}:${caller[3]}`,
      implementIn: issue[1],
      errorAt: `${issue[2]}:${issue[3]}`,
      message: e?.message,
    };

  console.log("Error trace ", formattedErr);
  return formattedErr;
}


function doSomething () {
   try {
    let a = 18; let c;
    console.log("calculation started...");
    c = b/a;
    console.log("result ", c)
 }
  catch (err) {
    printError(err)
  }
 }

 // invoke function
 doSomething()

本文标签: javascriptObtaining the name of the current function being executed in NodejsStack Overflow