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;
@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