how to read a random line/lines from a file in node.js

2,139 views
Skip to first unread message

sudan.k...@wezkoz.com

unread,
Feb 1, 2016, 11:27:23 AM2/1/16
to nodejs
how to read a random line/lines from a file  using node.js


Alwin de Leon

unread,
Feb 3, 2016, 4:28:27 PM2/3/16
to nodejs


On Tuesday, February 2, 2016 at 12:27:23 AM UTC+8, sudan.k...@wezkoz.com wrote:
how to read a random line/lines from a file  using node.js


//read a file
 fs = require('fs')
fs.readFile('/etc/hosts', 'utf8', function (err,data) { if (err) { return console.log(err); } data = data.split('\n'); });

Alwin de Leon

unread,
Feb 3, 2016, 4:28:39 PM2/3/16
to nodejs


On Tuesday, February 2, 2016 at 12:27:23 AM UTC+8, sudan.k...@wezkoz.com wrote:
how to read a random line/lines from a file  using node.js

fs = require('fs')
var data;
fs.readFile('filename.txt', 'utf8', function (err,rawData) {
  if (err) {
    return console.log(err);
  }
  data = rawData.split('\n');
});

function randomInt (low, high) {
    return Math.floor(Math.random() * (high - low) + low);
}

function getRandomLine(){
  return data[randomInt(0,data.length)];
}
Reply all
Reply to author
Forward
0 new messages