2012-06-02 2 views
17

필자는 자바 스크립트를 사용하여 한 줄씩 파일을 읽지 않았으며 phantomjs는 완전히 새로운 볼 게임입니다. 팬텀에 read() 함수가 있다는 것을 알고 있지만, 변수에 저장 한 후에 데이터를 조작하는 방법을 잘 모르겠습니다. 내 의사는 같은 것입니다 : 사람이 실제 코드 구문을 좀 도와주세요 수 있다면phantomjs javascript 라인별로 로컬 파일 읽기

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

    //do stuff here with the line 

} 

을, 나는 phantomjs 일반적인 자바 스크립트 또는 무엇을 수용할지 여부에 조금 혼란 스러워요.

답변

27

I하지 자바 스크립트 또는 PhantomJS 전문가하지만 다음 코드는 나를 위해 작동 해요 : 여기, 너무 늦게 비록

/*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

내가 시도 무엇이며 노력하고 있습니다 :

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

다음 파일에 전체 파일이 필요한 경우에 유용합니다. 그렇지 않으면 전체 파일을 읽는 것이 좋지 않습니다 (특히 입력 파일이 큰 경우) –

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

IMO는 내장 된 readLine() 함수를 사용하므로 더 나은 대답입니다. 관습을 다할 필요가 없다. –

+2

동의, 이것이 더 나은 대답입니다. 필자는 file_h.atEnd()를 루프 조건으로 사용하기위한 대답을 조정할 것을 제안합니다. http://phantomjs.org/api/stream/method/read-line.html –

+1

참조이 버전을 사용해 보았지만 readLine() 메소드가 더 이상 사용되지 않는 것 같습니다 : https://nodejs.org/api/fs.html# fs_fs_open_path_flags_mode_callback – alemol

관련 문제