Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text file into variables with javascript

I have a text file located on the server that contains a list of events with their target time. It looks something like the following:

2012/02/11-10:00:00 EventStart Red
2012/02/11-10:10:00 EventStop Green
...

What I need to do is somehow read the text file and based on the current time select the next upcoming event and assign each element for that event to a variable. So for example if the time is currently 2012.02.11-10:08:00, javascript variables time = '2012/02/11-10:10:00'; title = 'EventStop'; color = 'Green'; would be created.

I'm able to read the text file with:

jQuery.get('schedule.txt',function(data){
  alert(data);
});

Just don't know where to go from there, or if that's even the best way to start. I do have control over the formatting of the text file, so modifying that is an option.

like image 577
codybuell Avatar asked Feb 14 '12 21:02

codybuell


2 Answers

You say you can modify the file's contents, so I suggest converting it to JSON (and separating the date/time).

[{"date": "2012/02/11", "time": "10:00:00", "title": "EventStart", "color": "Red"}, {"date": "2012/02/11", "time": "10:10:00", "title": "EventStop", "color": "Green"}]

Then you can use getJSON to get/parse it.

jQuery.getJSON('schedule.txt',function(data){
    // data is an array of objects
    $.each(data, function(){
       console.log(this.title); // log each title
    });
});

From here, you can read the times and figure out which one is the latest. Something like this should work:

if(Date.now() <= Date.parse(this.date+' '+this.time))

So, putting it all together:

jQuery.getJSON('schedule.txt',function(data){
    var matchedSchedule = {};
    // data is an array of objects
    $.each(data, function(){
       if(Date.now() <= Date.parse(this.date+' '+this.time)){
          matchedSchedule = this;  // If time matches, set a variable to this object
          return false; // break the loop
       }
    });
    console.log(matchedSchedule.title);
    // to set a "global" variable, add it to `window`
    window.eventTitle = matchedSchedule.title;
});
like image 100
Rocket Hazmat Avatar answered Oct 06 '22 00:10

Rocket Hazmat


Without changing your text file

$.get('sometext.txt',function(data){
    var perLine=data.split('\n');
    var myVars=[];
    for(i=0;i<perLine.length;i++)
    {
    var line=perLine[i].split(' ');
    myVars[i]={
        'time':line[0],
        'event':line[1],
        'color':line[2]
        }
    }
    console.log(myVars);
    console.log(myVars[0].time);
    console.log(myVars[0].event);
    console.log(myVars[0].color);
});
like image 28
The Alpha Avatar answered Oct 05 '22 23:10

The Alpha