phantomjs javascript逐行读取本地文件 [英] phantomjs javascript read a local file line by line
问题描述
我从来没有使用过javascript来逐行读取文件,而phantomjs对我来说是一个全新的游戏。我知道幻像中有一个read()函数,但我不完全确定在将数据存储到变量后如何操作数据。我的伪代码类似于:
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:
filedata = read('test.txt');
newdata = split(filedata, "\n");
foreach(newdata as nd) {
//do stuff here with the line
}
如果有人可以帮我解决真正的代码语法问题,我对phantomjs是否会接受典型的javascript或者什么感到困惑。
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.
推荐答案
我不是JavaScript或PhantomJS专家,但以下代码适用于我:
I'm not JavaScript or PhantomJS expert but the following code works for me:
/*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();
这篇关于phantomjs javascript逐行读取本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!