开发者

Read lines from file in array

I have file main.log something like :

10-01-1970 01:42:52 Bus_Power devic开发者_Python百科e 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']


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.


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.


Say you're reading a text/log file, the following codes are modified from another post of stackflow.com,

var contentType = "application/x-www-form-urlencoded; charset=utf-8";

var request = new XMLHttpRequest(); 
request.open("GET", 'test.log', false);
request.setRequestHeader('Content-type', contentType);

if (request.overrideMimeType) request.overrideMimeType(contentType);

// exception handling
try { request.send(null); } catch (e) { return null; }
if (request.status == 500 || request.status == 404 || request.status == 2 || (request.status == 0 && request.responseText == '')) return null;

lines = request.responseText.split('\n')
for( var i in lines ) {
    console.log(lines[i]);
}

Problems may caused by encoding/decoding issue, so we may need exception handing as well. For more information about XMLHttpRequest, pls visit here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜