I want to write a function in javascript that reads text file and if it contains any javascript function in that text file then instead of reading it just as text, my function will read it as javascript.
Like:
const toBeRead = () => true; //This function is in text file
Above function is in text file and I want to read it as javascript. Currently I am reading this as a string but wanted to take output from it which is true.
Editing for better demonstration. Here is my function after using eval()
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function (e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split("\n");
let array = [];
words.map((word) => {
if (word.substring(0, 6) === "const ") {
if (word.includes("=>")) {
if (word.includes("=")) {
alert(word); //It shows const toBeRead=()=>true;
alert(eval(word)); // It shows undefined
array.push(word);
}
}
}
return array;
});
alert(array);
};
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
Actually I am creating a rule for coding convention like if functions return boolean then it should start with "is/has". Like const isFuncTrue=()=>true; Don't have rule defined in Eslint!
Two methods
eval(jsstr)
- not recommendedExample in browser - will not run if no DOM