phantomjs javascript逐行读取本地文件

zol*_*tar 18 javascript phantomjs

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

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

  //do stuff here with the line

}
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*kas 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();
Run Code Online (Sandbox Code Playgroud)


Kis*_*ngi 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();
Run Code Online (Sandbox Code Playgroud)

  • 同意,这是更好的答案.我建议调整使用file_h.atEnd()作为循环条件的答案.见http://phantomjs.org/api/stream/method/read-line.html (2认同)

sud*_*pto 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();
Run Code Online (Sandbox Code Playgroud)