How to load a table file in JavaScript synchronously

I came across this particular method for accessing a local text file.

However, I am facing an issue as I do not want the file to be read asynchronously. My goal is to have the function read the file and return the output as a string variable instead.

The format of my file is as follows:

time    acceleration    velocity    position
0   0   0   0
0.1 0.7584280404    0.075842804 0.0075842804
0.2 0.1291023633    0.0887530404    0.0164595844
0.3 0.4040327317    0.1291563135    0.0293752158
0.4 0.8891570587    0.2180720194    0.0511824177
0.5 0.3481323377    0.2528852532    0.0764709431
0.6 0.8920292137    0.3420881745    0.1106797605
0.7 0.7375283292    0.4158410075    0.1522638613
0.8 0.2647998196    0.4423209894    0.1964959602
0.9 0.633358462 0.5056568356    0.2470616438
1   0.3901214569    0.5446689813    0.3015285419
1.1 0.4712272086    0.5917917022    0.3607077121
1.2 0.693854515 0.6611771537    0.4268254275
1.3 0.4248616176    0.7036633154    0.497191759

The extracted data will be stored in obj with the following fields:

obj.time
obj.acceleration
obj.velocity
obj.position

These values need to be retrieved from the first row of the text file. All operations are conducted locally, so the loading time of heavy js libraries is not a concern. If anyone knows of a shortcut that meets my requirements, please share it. Alternatively, if there is no existing library, guidance on how to read a file synchronously would also be appreciated.

Answer №1

To retrieve the contents of a file and parse the data on your own, you can utilize a get request. By using the jQuery get method (or any other library or even making XMLHttpRequests manually), you can achieve this:

 $.ajax({
     url: 'http://domain.com/path/to/your/file.txt',
     async: true
   }).
   success(function (data) {
     var parsedData = parseMyFormat(data);
     console.log(parsedData[0].position);
   });

 function parseMyFormat (data) {
   var parsed = [];
   // Split the data by new line and iterate through each line
     var item = {};
     // Split each line by tab (\t) and assign values to respective properties
        item.time = col[0];
        item.acceleration = col[1];
        item.velocity = col[2];
        item.position = col[3];
     parsed.push(item);
 }

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

Storing the information filled out in the form and utilizing it to navigate to the correct destination URL

With the generous assistance and insightful advice from members of Stack Overflow, I am nearing completion of my quiz project. However, I do have a few lingering questions regarding some final touches needed for the project. Before delving into those quest ...

Implementing Jquery validation to check for duplicates when submitting an email form in Laravel

Hi, in my current Laravel project I am implementing a feature to check if an email is unique or not. At the front end, I have integrated jQuery code as shown below: blade.php page user_email: { required: true, email: true, remote: { ur ...

Leveraging AJAX to return JSON data to the Android nanoHTTPd method

Hello everyone, I am attempting to send JSON data to my Android app using jQuery Ajax and NanoHTTPd as the web server. However, I'm having trouble accessing the POST data. Here is the code snippet where I make the Ajax call: var reqData = JSON.string ...

Executing a function on page load instead of waiting for user clicks

I've been researching a problem with onclick triggers that are actually triggered during page/window load, but I haven't been able to find a solution yet. What I need is the ID of the latest clicked button, so I tried this: var lastButtonId = ...

Can you explain the purpose of the equals sign in ngRepeat?

Can you explain the significance of the equals sign in the ng-repeat attribute value? <li ng-repeat="person in people = (people | orderBy: firstname)"> rather than using: <li ng-repeat="person in people | orderBy: firstname"> I coul ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

What is the best way to send data from ajax to a django view?

I have a script for ajax that retrieves the public key and sends other details to the Stripe server for payment. However, I am struggling with sending the dynamic value of the price to item_line. fetch("/config/") .then((result) => { return re ...

Issue "Excessive large sharp variable amount" encountered during ajax request

I'm attempting to retrieve data from a different domain using jQuery. Take a look at the code snippet below: $.ajax({ type: "GET", dataType: "script", url: "http://www.example.com/ajax.php", data: 'id=5', success: functi ...

What is the best way to change function.bind(this) to an arrow function in a react native application?

I am attempting to convert my function into an arrow function, but I keep encountering an error of undefined when passing props. <TextInput style={styles.input} value={formState.inputValues.title} onChangeText={textCh ...

Unable to transmit the search query as a parameter

I am working on a dropdown display with autocomplete feature using the select2 jQuery plugin. However, I have encountered an issue where the search term entered in the search box is not being passed as a parameter to the controller method. Here is my curre ...

What could be causing jQuery document ready to restrict access to global variables?

Currently, I am working on a project that involves three separate JavaScript files (example1.js, example2.js, and example3.js) being scripted into a single HTML file (index.html). These JS files are responsible for making an API call and manipulating the r ...

Uncovering Inline Styles Infused with Javascript for Effective Debugging of Javascript Code

SITUATION: I have recently inherited a website from the previous developer who has scattered important functions across numerous lengthy JS files. I am struggling to track down the source of an inline CSS style within the JS or identify which function is d ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

Try employing an alternative angular controller when working with the bootstrap modal

I am trying to implement a bootstrap modal in my main HTML file, and I need some help on how to call another Angular controller for the modal. The button that triggers the modal is within a div that already has an Angular controller, and this is causing th ...

React Native - Listview triggering multiple refreshes when pulled down

As I attempt to implement the onScroll function for ListView to detect when a user has pulled the list down beyond a certain pixel value in order to trigger an AJAX call and refresh the list, I am facing an issue where it fires multiple times leading to a ...

Struggling to connect CSS and JavaScript files to index.html on Heroku while utilizing Node.js

Trying to set up a Tic Tac Toe game in my app.js file, but encountering some issues with linking files in index.html. app.set('port', (process.env.PORT || 5000)) //serve static files in the public directory app.use(express.static('public& ...

What is the reason for $http.get not requiring a return value?

I am currently developing an angular application and I have a controller that interacts with a service. The controller sends a URL to the service, which then makes a GET request to that URL and receives JSON data in return. Within this JSON data is a URI f ...

Comprehending the concept of error and data callbacks in functions

I'm feeling a bit puzzled about how the function(err, data) callback operates. Is the first argument always designated to handle errors? And what happens with the rest of the arguments in a scenario like function(x, y, z, a, b, c)? How exactly does ...

Cool ways to showcase HTML content in AngularJS

I am completely new to AngularJS. My goal is to display HTML content on the view using AngularJS. I initially tried using ng-model, but it displayed HTML content as a string on the view. After that, I attempted to use ng-bind-html which worked for the in ...