6

Sorry for so dumb question,

How i can in NodeJS read from file string by string some value, for example - url, and do operation with each string eventually?

var contents = fs.readFileSync('test.txt', 'utf8');

and what then?

It's need for browserstack+selenium testing. I want run some links one-by-one, from file and do something with them.

Changed code below: from

console.log(lines[i++])

to

line = (lines[i++])
driver.get(line);
driver.getCurrentUrl()
                .then(function(currentUrl) {
                   console.log(currentUrl);

But it works once.

And

var str=fs.readFileSync('test.txt');
str.split(/\n/).forEach(function(line){})


C:\nodejstest>node test1.js
C:\nodejstest\test1.js:57
str.split(/\n/).forEach(function(line){
    ^

TypeError: str.split is not a function
    at Object.<anonymous> (C:\nodejstest\test1.js:57:5)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:142:18)
    at node.js:939:3

Works! Much thanx!

Boris
  • 115
  • 1
  • 11

2 Answers2

11

Another (simpler) method would be to read the entire file into a buffer, convert it to a string, split the string on your line-terminator to produce an array of lines, and then iterate over the array, as in:

var buf=fs.readFileSync(filepath);

buf.toString().split(/\n/).forEach(function(line){
  // do something here with each line
});
Rob Raisch
  • 15,416
  • 3
  • 43
  • 55
0

read file with readable stream and do your operation when you find '\n'.

var fs=require('fs');
var readable = fs.createReadStream("data.txt", {
    encoding: 'utf8',
    fd: null
});
var lines=[];//this is array not a string!!!
readable.on('readable', function() {
    var chunk,tmp='';
    while (null !== (chunk = readable.read(1))) {
        if(chunk==='\n'){
            lines.push(tmp);
            tmp='';
        //    this is how i store each line in lines array
        }else
            tmp+=chunk;
    }
});
// readable.on('end',function(){
//     console.log(lines);    
// });
readable.on('end',function(){
    var i=0,len=lines.length;
    //lines is #array not string
    while(i<len)
        console.log(lines[i++]);
});

See if it works for you.

vkstack
  • 1,484
  • 9
  • 21