2

I am trying to get a file and assign it to a array and randomly get a string from the array and print it on the html. I have done this whole project in python. But I've never programmed with JavaScript and am not sure how to proceed. I think the issue may be with the file assigning to array but I am confused.

<!doctype html>
<html>
<head>
<title>Julia Mount</title>
</head>
<body onload="ll()">
<style>
    body{
    background-color:lime;  
}
#wat{
    padding-top:auto;
    margin: auto;
    text-align:center;
}
</style>

<script type="text/javascript">
    var fs = require("fs");
    var text = fs.readFileSync("./mytext.txt");
    var textByLine = text.split("\n")
    var ll = ["wat","idk"   
];
               //stuff im trying
    //var randomIndex = Math.floor(Math.random() * textArray.length); 
    //var randomElement = textArray[randomIndex];
    //document.getElementById("ll").innerHTML = randomElement;
    ll.toString();
    //document.getElementById("ll").innerHTML = ll;

</script>
<h1 id="wat">I love </h1>
    <p></p>
    <script type="text/javascript">
        document.write($ll)     
      </script>
</body>
</html>
j08691
  • 204,283
  • 31
  • 260
  • 272
David
  • 71
  • 8

2 Answers2

0

JavaScript has no native mechanisms to access files. It depends on functions being provided by the host environment.

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");

These are functions provided by Node.js but not by web browsers.

To run this code, you need to remove it from the HTML page and run it using Node.js.

See this question for information about reading files using a JS embedded in a webpage.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I'm trying to get this all in a single html file to send to my gf. Il just have to remove that – David Apr 08 '18 at 20:33
0

as mentioned in the other answer, you're trying to use a server side ( nodeJs ) code to get the file in the browser, to get the content of a .txt file in the browser ( html side ) you'll need to do an Ajax request with XMLHttpRequest, wrap it in a function and return a Promise to make sure everything is executing Synchronously

replace theses lines :

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n");

with :

var textByLine;

function readTextFile(file, cb) {
  return new Promise((resolve, reject) => {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function() {
      if (rawFile.readyState === 4) {
        if (rawFile.status === 200 || rawFile.status == 0) {
          resolve(rawFile.responseText);
        }
      }
    }

    rawFile.send(null);
  });

}

readTextFile('mytext.txt').then((text) => {
  textByLine = text.split("\n");
});

// ... rest of you code ...
Taki
  • 17,320
  • 4
  • 26
  • 47
  • Its going better, got some other stuff im working on now though. Thank you for your help. – David Apr 11 '18 at 00:43