How to read content of text file as Javascript?

454 views Asked by At

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!

1

There are 1 answers

3
mplungjan On

Two methods

  1. eval(jsstr) - not recommended
  2. script:

Example in browser - will not run if no DOM

const str = `const toBeRead = () => true; //This function is in text file`
const scr = document.createElement("script")
scr.textContent = str;
document.body.appendChild(scr)
console.log(toBeRead())