2012-06-02 5 views
17

Nigdy nie używałem javascript do czytania linii pliku po wierszu, a phantomjs to dla mnie zupełnie nowa gra w piłkę. Wiem, że istnieje funkcja read() w phantom, ale nie jestem całkowicie pewien, jak manipulować danymi po przechowywaniu go do zmiennej. Moja pseudokod jest coś takiego:phantomjs javascript czyta lokalną linię plików według linii

filedata = read('test.txt'); 
newdata = split(filedata, "\n"); 
foreach(newdata as nd) { 

    //do stuff here with the line 

} 

Jeśli ktoś mógłby mi pomóc z rzeczywistym składni kodu, jestem nieco mylić, czy phantomjs zaakceptuje typowy javascript lub co.

Odpowiedz

27

Nie jestem ekspertem JavaScript lub PhantomJS ale następujący kod działa dla mnie:

/*jslint indent: 4*/ 
/*globals document, phantom*/ 
'use strict'; 

var fs = require('fs'), 
    system = require('system'); 

if (system.args.length < 2) { 
    console.log("Usage: readFile.js FILE"); 
    phantom.exit(1); 
} 

var content = '', 
    f = null, 
    lines = null, 
    eol = system.os.name == 'windows' ? "\r\n" : "\n"; 

try { 
    f = fs.open(system.args[1], "r"); 
    content = f.read(); 
} catch (e) { 
    console.log(e); 
} 

if (f) { 
    f.close(); 
} 

if (content) { 
    lines = content.split(eol); 
    for (var i = 0, len = lines.length; i < len; i++) { 
     console.log(lines[i]); 
    } 
} 

phantom.exit(); 
5

Chociaż zbyt późno, tutaj jest to, co próbowałem i działa:

var fs = require('fs'), 
    filedata = fs.read('test.txt'), // read the file into a single string 
    arrdata = filedata.split(/[\r\n]/); // split the string on newline and store in array 

// iterate through array 
for(var i=0; i < arrdata.length; i++) { 

    // show each line 
    console.log("** " + arrdata[i]); 

    //do stuff here with the line 
} 

phantom.exit(); 
+0

Jest to dobre, jeśli cały plik jest wymagany do następnego procesu. W przeciwnym razie nie jest dobrym pomysłem przeczytanie całego pliku (szczególnie, gdy plik wejściowy jest duży). –

21
var fs = require('fs'); 
var file_h = fs.open('rim_details.csv', 'r'); 
var line = file_h.readLine(); 

while(line) { 
    console.log(line); 
    line = file_h.readLine(); 
} 

file_h.close(); 
+0

Lepsza odpowiedź tutaj, IMO, ponieważ wykorzystuje wbudowaną funkcję readLine(); nie trzeba robić nic niestandardowego. –

+2

Zgadzam się, to jest lepsza odpowiedź. Sugerowałbym jednak poprawienie odpowiedzi na użycie file_h.atEnd() jako warunku pętli. Zobacz http://phantomjs.org/api/stream/method/read-line.html –

+1

Próbowałem tej wersji, ale wydaje się, że metoda readLine() jest przestarzała: https://nodejs.org/api/fs.html# fs_fs_open_path_flags_mode_callback – alemol

Powiązane problemy