-1

How to write a function that returns a line from file with nodeJS? The program runs in the loop, and each time you call the function should return a new string. And if the file ends begins again, with the first line.

This function takes randomly, how to do consistently?

 var fs = require('fs');

 // Get random line from file
 function getRandSocks() {
   var socks = fs.readFileSync('socks.txt').toString().split("\n");
   var randsock = socks[Math.floor(Math.random()*socks.length)];
   return randsock.split(':');
 }

 function loop() {
   // ...
   var socks = getRandSocks();
   console.log('host: '+socks[0]+'port :'+socks[1]);
   //...
   loop();
 }
slaw
  • 55
  • 1
  • 10
  • possible duplicate of [Javascript Random Seeds](http://stackoverflow.com/questions/521295/javascript-random-seeds) – msw Aug 30 '15 at 22:18

1 Answers1

0

Perhaps this would help. This gets the next line and wraps back to the start. It is based on the given getRandSocks function with minimal change.

var current_line = 0;
function getNextLines() {
   var socks = fs.readFileSync('socks.txt').toString().split("\n");
   var randsock = socks[current_line % socks.length];
   current_line = (current_line + 1) % socks.length
   return randsock.split(':');
}
Dan D.
  • 73,243
  • 15
  • 104
  • 123