Last active
February 7, 2020 22:04
-
-
Save JuanFelix88/9e775a8c4f0f86ca4d0ab7b74ae74746 to your computer and use it in GitHub Desktop.
Get variable name by call stack in NODE.JS (unsafe code)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from "fs"; | |
import { resolve } from "path"; | |
function getVarName(variable: any): string { | |
const stack2: string = new Error().stack.split(/at/g)[2].trim(); | |
const splitted = stack2.substr(20, stack2.length - 21).split(/:/); | |
const lineAndPosition = splitted.slice(2).map(item => parseInt(item)); | |
const fileData = fs.readFileSync( | |
resolve(splitted.slice(0, 2).join(":")), | |
"utf8" | |
); | |
const line = fileData.split("\n")[lineAndPosition[0] - 1]; | |
let state: 0 | 1 = 0; | |
let name: string = ""; | |
for (let i = lineAndPosition[1] - 1; i < line.length; i++) { | |
if (line[i] === "(") { | |
state = 1; | |
continue; | |
} | |
if (line[i] === ")") { | |
state = 0; | |
continue; | |
} | |
if (state === 1) name += line[i]; | |
} | |
if (!/^[A-Za-z0-9$]+$/i.test(name)) return; | |
return name; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment