首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >phantomjs javascript逐行读取本地文件

phantomjs javascript逐行读取本地文件
EN

Stack Overflow用户
提问于 2012-06-03 04:49:38
回答 3查看 15.3K关注 0票数 18

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

代码语言:javascript
复制
filedata = read('test.txt');
newdata = split(filedata, "\n");
foreach(newdata as nd) {

  //do stuff here with the line

}

如果有人能帮助我实现真正的代码语法,我对phantomjs是否会接受典型的javascript之类的东西感到有点困惑。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-08-01 16:15:53

我不是JavaScript或PhantomJS专家,但以下代码适用于我:

代码语言:javascript
复制
/*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();
票数 27
EN

Stack Overflow用户

发布于 2013-06-24 02:54:42

代码语言:javascript
复制
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();
票数 22
EN

Stack Overflow用户

发布于 2013-05-05 00:38:49

尽管为时已晚,但以下是我已经尝试并正在发挥作用的方法:

代码语言:javascript
复制
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();
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10865849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档