phantomjs javascript逐行读取本地文件

时间:2012-06-02 20:49:38

标签: javascript phantomjs

我从来没有使用过javascript来逐行读取文件,而phantomjs对我来说是一个全新的游戏。我知道幻像中有一个read()函数,但我不完全确定在将数据存储到变量后如何操作数据。我的伪代码类似于:

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

  //do stuff here with the line

}

如果有人能用真正的代码语法帮助我,我对phantomjs是否会接受典型的javascript或者什么感到困惑。

3 个答案:

答案 0 :(得分:27)

我不是JavaScript或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();

答案 1 :(得分: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();

答案 2 :(得分: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();