19

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.

zoltar
  • 706
  • 2
  • 7
  • 20

3 Answers3

28

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();
Darius Kucinskas
  • 10,193
  • 12
  • 57
  • 79
22
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();
Darius Kucinskas
  • 10,193
  • 12
  • 57
  • 79
Kishore Relangi
  • 1,928
  • 16
  • 18
  • The better answer here, IMO, since it uses the built in readLine() function; no need to do anything custom. – Craig Sefton Mar 14 '14 at 12:13
  • 2
    Agreed, this is the better answer. I would suggest tweaking the answer to use file_h.atEnd() as the loop condition, though. See http://phantomjs.org/api/stream/method/read-line.html – Aaron Bruce Apr 11 '14 at 17:22
  • 1
    I tried this version but it seems that readLine() method is deprecated : https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback – alemol Sep 01 '15 at 20:51
  • great ideas @Kishore Relangi – gumuruh Jul 18 '16 at 07:37
5

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();
sudipto
  • 2,472
  • 1
  • 17
  • 21
  • This is good if entire file is required for next process. Otherwise it is not a good idea to read the whole file (especially when the input file is big) – Kishore Relangi Apr 02 '14 at 12:28