Skip to content

Instantly share code, notes, and snippets.

@gurisko
Last active May 11, 2024 05:41
Show Gist options
  • Save gurisko/2e6936ea6679afd2d313fdbdf0a18b00 to your computer and use it in GitHub Desktop.
Save gurisko/2e6936ea6679afd2d313fdbdf0a18b00 to your computer and use it in GitHub Desktop.
[NodeJS] Get the current function name or any other function while using strict mode
'use strict';
const findFirstOccurrence = (string, searchElements, fromIndex = 0) => {
let min = string.length;
for (let i = 0; i < searchElements.length; i += 1) {
const occ = string.indexOf(searchElements[i], fromIndex);
if (occ !== -1 && occ < min) {
min = occ;
}
}
return (min === string.length) ? -1 : min;
}
const functionName = (func = null) => {
if (func) {
if (func.name) {
return func.name;
}
const result = /^function\s+([\w\$]+)\s*\(/.exec(func.toString());
return result ? result[1] : '';
}
const obj = {};
Error.captureStackTrace(obj, functionName);
const {stack} = obj;
const firstCharacter = stack.indexOf('at ') + 3;
const lastCharacter = findFirstOccurrence(stack, [' ', ':', '\n'], firstCharacter);
return stack.slice(firstCharacter, lastCharacter);
}
module.exports = functionName;
@lveillard
Copy link

This is just awesome!
Do you think it is possible also to get the parent function's name?

@lveillard
Copy link

lveillard commented Jul 23, 2020

So for other coming here the answer is YES and you can just add this line:
const newStack = stack.split("\n").slice(NUMBER).join("\n");
after:
const {stack} = obj;
Where NUMBER is the amount of jumps you want to do to the past (Number = 1 => first parent)
And changing the next stack instances by newStack

@alex-cory
Copy link

doesn't work in Safari

@lveillard
Copy link

lveillard commented Oct 11, 2021

doesn't work in Safari

Does something work in Safari?

If it is not working in Safari check also in chrome from an Iphone. There are some chances is not even working there. Those s*****s are not happy enough complexing their stuff, they have to limit other's software

@alex-cory
Copy link

Chrome on iOS is still webkit (aka safari). It's just a different UI.

@alex-cory
Copy link

stacktracey seems to work cross browser pretty well

@flipperlite
Copy link

Great job. This is exactly what I was looking for without instantiating a new Error (although it still parses a call stack). Confirmed working in Node v16.13.0. It also may not be clear until you're using it that just calling the function without passing a function will get the current function's name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment