-3

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!

Suleman Ahmad
  • 452
  • 1
  • 5
  • 14
  • Are you looking for [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)? – David Sep 30 '20 at 13:03
  • I have used eval() but still not getting return from function defined in text file. I am reading text file line by line as it may contains more functions. – Suleman Ahmad Sep 30 '20 at 13:04
  • Can you demonstrate your attempt and indicate specifically how it's not working? – David Sep 30 '20 at 13:05
  • 1
    What are you trying to do? What's the big picture? Is this an XY problem? Why do you have JavaScript in a text file? Is this node.js or browser or something else? – Wyck Sep 30 '20 at 13:06
  • That's because `eval('x = 5')` --> 5. but `eval('const x = 5')` --> undefined. – Wyck Sep 30 '20 at 13:08
  • @David I want return value from function in my text file. By doing alert(eval(function)); it shows undefined in alert() where function value is "const abc=()=>true;" – Suleman Ahmad Sep 30 '20 at 13:17
  • @SulemanAhmad: In that example where do you define/assign `function`? A [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) would really help demonstrate the problem. – David Sep 30 '20 at 13:20
  • @Wyck Do I have to split the function with the const in case there is arrow function defined in text file? – Suleman Ahmad Sep 30 '20 at 13:20
  • `eval('const x = 5')` is not an expression that evaluates to `5`. it evaluates to `undefined`. After `eval('const x = 5')` a subsequent `eval('x')` won't even evaluate to `5` – Wyck Sep 30 '20 at 13:21
  • Your premise that "output from it is true" is false. The output of `const toBeRead = () => true` is undefined. It does, however, introduce a constant called `toBeRead`. If you appended the text `; return toBeRead` Then you might have a chance of eval returning the function object, but it still won't return `true`. You're gravely mistaken about how JavaScript works and your expectations are inconsistent with how the language actually performs. – Wyck Sep 30 '20 at 13:25
  • @David There is a map() used to parse line by line in my javascript function and I have that logic defined in my javascript function. I did console the value and function contains arrow function. I just want to get return from it and by using eval() alert is showing undefined! – Suleman Ahmad Sep 30 '20 at 13:25
  • @David Edit the post for you! – Suleman Ahmad Sep 30 '20 at 13:37
  • Can you just trim off the `const` part? `theValue = eval(word.replace(/^const/,'')` – Wyck Sep 30 '20 at 13:37
  • Can we see an example (multiple lines) of what's in the text file? Do different lines depend on each other or anything else external? – Wyck Sep 30 '20 at 13:40
  • @Wyck for the moment there is only one line in text file on which I am testing. Later on work with multiple ones. – Suleman Ahmad Sep 30 '20 at 13:42
  • I still have no idea why you're going about it this way. You're way off track. This is not the way JavaScript is to be used. Why are you parsing JavaScript line at a time like this? – Wyck Sep 30 '20 at 13:46
  • @Wyck to detect if there is any arrow function defined in text file if yes, then get return value from it. – Suleman Ahmad Sep 30 '20 at 13:48
  • You told me *what* you wanted to do, but did not tell me*why*. Maybe you want [esprima](https://esprima.org/) To parse the file and then see if any arrow functions were parsed. – Wyck Sep 30 '20 at 13:54
  • Actually I am creating a rule for coding convention like if functions return true then it should start with "is/has". Like const isFuncTrue=()=>true; Dont have rule defined in Eslint! – Suleman Ahmad Sep 30 '20 at 13:55

1 Answers1

3

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())
mplungjan
  • 169,008
  • 28
  • 173
  • 236