Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines from file in array

I have file main.log something like :

10-01-1970 01:42:52 Bus_Power device 9 up
10-01-1970 01:42:52 External_Power device 9 up
10-01-1970 01:42:57 Bus_Power device 1 down
10-01-1970 01:42:57 Bus_Power device 2 down

Every row is one data. How to parse this in array of rows using Dojo or plain JavaScript ?

for example :

['10-01-1970 01:42:52 Bus_Power device 9 up','10-01-1970 01:42:52 External_Power device 9 up']
like image 692
Damir Avatar asked Apr 12 '26 02:04

Damir


2 Answers

var xhr = new XMLHttpRequest();

xhr.open('GET', 'main.log', false);
xhr.send(null);

var log = xhr.responseText.split('\n');

// `log` is the array of logs you want

Note: Done synchronously, for simplicity, as no details were given about application of this functionality.

like image 173
James Avatar answered Apr 13 '26 14:04

James


If you have the file into a string (say 'text'), then you can do:

var lines = text.split("\n");

Check if your file on the server terminates lines with just one line-feed (UNIX-style) or a CR-LF pair (Windows-style).

How do you get the file into a string in the first place? You can use dojo.xhrGet(...). Look it up in the Dojo docs.

like image 38
Stephen Chung Avatar answered Apr 13 '26 15:04

Stephen Chung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!