简体   繁体   中英

Javascript load table file synchronously

I am aware of this implementation for calling a local text file.

My problem is that, I don't want it read the file asynchronously. Instead I want the function reads the file and returns the output as a string variable.

My file is in this format:

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 output will be stored in obj containing the following fields

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

These fields must be obtained from the first row of the text file. Everything is done from localhost and nothing is remote so I do not care about how long it takes to load heavy js libraries. It would be great if somebody lets me know if there is a shortcut for what I am looking for. If there is no library doing it, please let me know how at least I can read a file synchronously.

You can use a get request to download the file content and parse data yourself. Using jQuery get method (you can basically replace jQuery with any other lib or forget about any extra library and make xhr requests manually):

 $.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 your data by new line and iterate over lines
     var item = {};
     //split each line by tab (\t) and put 
        item.time = col[0];
        item.acceleration = col[1];
        item.velocity = col[2];
        item.position = col[3];
     parsed.push(item);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM