NodeJS, fs.readFileSync string-by-string reading, and operating. How?

Boris picture Boris · Mar 28, 2016 · Viewed 8.4k times · Source

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!

Answer

Rob Raisch picture Rob Raisch · Mar 28, 2016

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
});