I'm feeling a bit lost on where to go next with this JavaScript

I've been working on a project in Python where I need to retrieve a file, store it in an array, and display a random string from the array on HTML. However, I have no experience with JavaScript and am unsure how to proceed. I suspect there may be an issue with assigning the file to the array, which is causing confusion.

<!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>

Answer №1

Just like mentioned in another response, if you want to retrieve a text file in the browser using server-side code (such as Node.js), you'll need to perform an AJAX request with XMLHttpRequest on the client side. This involves wrapping the request in a function and returning a Promise to ensure synchronous execution.

To achieve this, replace the following 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 your code ...

Answer №2

JavaScript does not have built-in capabilities for file access. It relies on functions that are provided by the specific hosting environment.

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

These particular functions are available in Node.js, but they are not accessible in web browsers.

To execute this code, it should be separated from the HTML document and run using Node.js.

For guidance on reading files in JavaScript embedded within a webpage, refer to this question.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the appearance of an element that is being inserted using .before() by utilizing a variable

Using the jQuery function .before(), I am creating an element in this format: d.children().first().before("<div class='test-div'><span class='test-span'>" + text + "</span></div>") I want to style the span dyna ...

Displaying search results from a PHP query in an HTML text box

Within my PHP page, I am populating a table with the results of a query using the following code: <?php $json=file_get_contents("http://www.example.com/myfile.php"); $data = json_decode($json); if (count($data->result)) { echo "<table id= &apos ...

Vue Websockets twofold

I am experiencing some issues with Laravel/Echo websockets and Vue.js integration. I have set up everything as required, and it works, but not quite as expected. The problem arises when I refresh the page and send a request - it displays fine. However, if ...

What could be causing the state object in React to not be updating correctly? There seems to be a discrepancy between the expanded and

Displayed on the console is a screenshot showing <br><br> I am working with React.js, and the object displayed in the image is an element within an array that is part of the state object. I'm puzzled by what's happening. The object a ...

Is it possible to trigger the alert message by utilizing this code snippet?

Is it possible to display a message using this function? var start_database = function() { alert('hello'); }; window.setTimeout(start_database, 1000); ...

A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not. I am struggling with creating a function to move ...

An efficient way to store a JavaScript-generated countdown timer in MySQL using PHP

Can anyone provide guidance on how to save a JavaScript-rendered countdown timer into a MySQL database using PHP? For example, I have a button that, when clicked, triggers the countdown timer to start. My issue lies in figuring out the best method to ensu ...

Is there a way to execute a javascript function that is located outside of my Angular application without having to import it?

I need to be able to trigger a JavaScript function that is located outside of my Angular app when a button is clicked. Unfortunately, it seems that importing the JavaScript directly into my Angular app isn't feasible for this task. The platform I am ...

I am retrieving data from a service and passing it to a component using Angular and receiving '[object Object]'

Searching for assistance with the problem below regarding my model class. I've attempted various approaches using the .pipe.map() and importing {map} from rxjs/operators, but still encountering the error message [object Object] export class AppProfile ...

Retrieve the status of the webpage using the "document.readyState" command within the JMeter WebDriver Sampler with JavaScript

I am relatively new to Selenium and WDS in Jmeter, so I could use some assistance. I'm having trouble writing code that waits for the entire page to load. I came across something like "return document.readyState", but I can't seem to implement it ...

Exploring the techniques for displaying and concealing div elements with pure JavaScript

Here's an example of code I wrote to show and hide div elements using pure JavaScript. I noticed that it takes three clicks to initially hide the div elements. After that, it works smoothly. I was attempting to figure out how to display the elements ...

How come the last word in CSS nested flexbox wraps even though there is space available?

I am facing an issue with a nested flex container setup. Below is the code snippet: <div class="parent-container"> <div class="child-container"> <span class="color-block"></span> <span>T ...

Can Bootstrap buttons be manipulated to mimic checkbox behavior effectively?

Looking to implement the data-toggle feature of Bootstrap for enabling users to choose their privilege level. I created a simple demonstration on JSFiddle, where the expected values are: None: 0 User: 1 Administrator: 2 User + Administrator = 3 The iss ...

Uploading a three.js canvas to the server without saving it as a file

Currently, I am in the process of saving an image to the server using a three.js script that I have created. The script looks like the following: actualCode(THREE); function actualCode(THREE) { //Rendering variables const renderer = new THREE.WebG ...

The AngularJS directive "ng-include" is used to dynamically

I am encountering an issue with ng-include not retrieving the file. What could be the reason for the problem in accessing a property from a link within ng-include? I would appreciate any assistance with resolving this matter. (function(){ var app = angu ...

Acquiring the item by referencing one of its property's values

Imagine you have a JSON structure that looks like this: [ { "name":"Foo" "nickname":"Lorem Ipsum" }, { "name":"Bar" "nickname":"Dolor S ...

Is there a way to locate classes containing underscores within them using Selenium?

Having trouble scraping a webpage with a class name containing an underscore, specifically this element: <span class="s-item__time-left">30m</span> == $0 I attempted to locate it by class name: time = driver.find_elements_class_name("s-item_ ...

The click interactions of SVG elements are altered when switching between <img> and <object> elements

I currently have 4 SVG buttons featured in the main menu of my personal website. https://i.stack.imgur.com/gA7En.png /----------------------------------------------------------------------------------------------------------------------------------/ Upo ...

Determine the number of days without including weekends and holidays using JavaScript

I am working on a code that calculates the total number of days excluding weekends and specified holidays. After researching on various platforms like stackoverflow and adobe forum, I have come up with the following code. If a public holiday falls on a w ...

React: The received value for the prop type must be a function, but it was an object

I'm stuck trying to make sense of this error message, and my online search has hit a dead end. Any insights would be greatly appreciated! Attention: Prop type validation failed - expected prop type `leoInfo` to be a function from the `prop-types` pack ...