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

Using Ajax with Laravel for Beginners

After clicking a button in my Laravel app, I want to update some data in the database using ajax without reloading the page. This is a simple ajax request where only a function in a controller needs to be invoked. I tried setting up the ajax request follo ...

Activating a link click inside a table with jquery

I have been attempting to trigger a click on an anchor within the table compareTable with the code below, however it does not appear to be working as expected. Would anyone be able to provide insight into a possible solution? $('#compareTable a' ...

Is it possible to create a button that can bring in a .css file?

Is there a way to create a button that imports styles from a .css file, or is it possible to change multiple CSS properties with buttons to create different website themes? This is the CSS file I have: .body { background-image: url("example.png"); } ...

Exploring the capabilities of Vue.js, including the use of Vue.set()

Just starting out with Vuejs and I have a query regarding the correct approach to achieve what I want. My Objective I aim to have some dates stored in an array and be able to update them upon an event trigger. Initially, I attempted using Vue.set, which ...

Tips for implementing a multi-layered accumulation system with the reduce function

Consider the following scenario: const elements = [ { fieldA: true }, { fieldB: true }, { fieldA: true, fieldB: true }, { fieldB: true }, { fieldB: true }, ]; const [withFieldA, withoutFieldA] = elements.reduce( (acc, entry) => ...

Tips for sending a callback function in Angular following an HTTP request

Currently, I am leveraging an angular controller to make an http post request to my express route. Subsequently, data is dispatched to my Gmail client via nodemailer. Although the $http request functions properly and emails can be received in my Gmail acco ...

Is there a way to deliberately trigger an error using Selenium WebDriverIO?

Is there a way to trigger an error using ChromeDriver with Selenium WebDriverIO? I'm not sure if there's a method like browser.fire('error'). ...

On the hunt for a specialized JavaScript library for input validation?

Have you ever come across a JavaScript library that allows for variable validation in a convenient chaining style like this one? For example: if(insertLibraryNameHere(myNumberInput).int().min(0).max(10)) This library also has checks for other data types ...

Using NGRX Effects to Load Data for a Specific Item in Angular

On my website, there is a page that displays a range of products from the store managed by a reducer called products. When an action PRODUCTS.LOAD_ALL is dispatched, it triggers an API call through an effect and then sends a PRODUCTS.LOAD_ALL_SUCCESS actio ...

When utilizing jQuery.Mockjax to simulate the JSON data, the Backbone.Collection.fetch() function consistently results in a 404 error

My setup is pretty straightforward: Main.js: (function($) { "use strict"; var Company = Backbone.Model.extend({ defaults: { title: "", description: "" }, initialize: function() { ...

Retrieving over 300,000 rows from elasticsearch and saving them as a .csv document

Hi there, I am currently working on a website in nodejs that utilizes an Elasticsearch database. One of my indexes, 'bigData*', contains 366,844 rows with each row consisting of 25 items, each being a different string of varying sizes (with a max ...

Is there a way for me to view the specifics by hovering over a particular box?

Whenever I hover over a specific box, detailed information appears, and when I move the mouse away, the details disappear. HTML <nav> <div> <div class="nav-container"> <a href="./about.html" ...

Steps for inserting new text in front of an element's existing text

Is there a way to insert text before the original content of an element? I know how to add text after using createTextNode, as shown in this example: $("#button").click(function() { $( ".text" ).append( document.createTextNode( " Hello" ) ); }); < ...

Check for mobile browser without having to refresh the page

Currently, I am facing an issue with closing the sidebar when the user clicks on Click Me button in mobile view using flexbox layout. The problem arises because the page needs to be refreshed for it to recognize if it's in mobile mode or not by utiliz ...

Different methods for modifying the height of an Angular datatable in response to the data provided

Encountering an issue with adjusting the height of a datatable when calling a webservice to populate it. A webpage features a collapsible div element alongside a datatable. Upon collapsing the div, the table's height is calculated and resized using i ...

Limiting the types of files a user can access through a web browser

Hey there! I have a unique question that sets it apart from others, as it involves restricting file types for users with a browser popup. My goal is to prevent users from selecting certain file types before they choose a file. I've come across some s ...

Monitor the user's attendance by utilizing two separate for loops

I'm currently developing an angularjs attendance tracking system and I'm facing challenges when it comes to accurately counting the number of days an employee is absent. Despite attempting to solve this issue with two nested for loops, I am still ...

Action type is not recognized: modification

After browsing through multiple forums, I haven't found a solution that works for my particular issue with my VueJS app. The problem arises when I try to input something in my first component. Below is the code snippet: main.js import Vue from &apos ...

Tips for increasing the height of a popover when clicked

When a user focuses on the password input, a popover displays information. At the bottom of the popover, there is a link. How can I make the popover expand when the user clicks on this link? I have tried adding an !important class for the height value, us ...

including a "continue" option to the jplayer interface

Does anyone know how to add a next button on jplayer? I've tried using the click function, but it doesn't seem to be working. The player is set up to use ajax to fetch songs and information about them. When one song ends, another is retrieved th ...