phantomjs javascript 逐行读取本地文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10865849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
phantomjs javascript read a local file line by line
提问by zoltar
I've never used javascript to read a file line by line, and phantomjs is a whole new ballgame for me. i know that there is a read() function in phantom, but I'm not entirely sure how to manipulate the data after storing it to a variable. My pseudocode is something like:
我从未使用 javascript 逐行读取文件,而 phantomjs 对我来说是一个全新的球赛。我知道幻像中有一个 read() 函数,但我不完全确定如何在将数据存储到变量后对其进行操作。我的伪代码是这样的:
filedata = read('test.txt');
newdata = split(filedata, "\n");
foreach(newdata as nd) {
//do stuff here with the line
}
If anyone could please help me with real code syntax, I'm a bit confused as to whether or not phantomjs will accept typical javascript or what.
如果有人可以帮助我了解真正的代码语法,我对 phantomjs 是否会接受典型的 javascript 或什么感到有些困惑。
回答by Darius Kucinskas
I'm not JavaScript or PhantomJS expert but the following code works for me:
我不是 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();
回答by Kishore Relangi
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();
回答by sudipto
Although too late, here is what I have tried and is working:
虽然为时已晚,但这是我尝试过并且正在运行的方法:
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();