Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phantomjs javascript read a local file line by line

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

}

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.

like image 889
zoltar Avatar asked Jun 02 '12 20:06

zoltar


2 Answers

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();
like image 78
Darius Kucinskas Avatar answered Oct 20 '22 06:10

Darius Kucinskas


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();
like image 23
Kishore Relangi Avatar answered Oct 20 '22 06:10

Kishore Relangi