簡體   English   中英

phantomjs javascript逐行讀取本地文件

[英]phantomjs javascript read a local file line by line

我從來沒有使用過javascript來逐行讀取文件,而phantomjs對我來說是一個全新的游戲。 我知道幻像中有一個read()函數,但我不完全確定在將數據存儲到變量后如何操作數據。 我的偽代碼是這樣的:

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

  //do stuff here with the line

}

如果有人能幫我解決真正的代碼語法,我對phantomjs是否會接受典型的javascript或者什么感到困惑。

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

雖然為時已晚,但這是我嘗試過的並且正在起作用:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM