Home > Software design >  Read random line from file node.js
Read random line from file node.js

Time:01-19

I'm trying to read a random line from a file with node.js. I can't seem to find a working solution. I tried searching all over the web but still wasn't able to find a working solution

I know how to read the whole file, but I don't know how to read 1 random file from the file.

const fs = require('fs')

var readMe = fs.readFileSync('proxies.txt', 'utf8');
console.log(readMe);

CodePudding user response:

By "random line" I guess you mean a line randomly chosen from among all the lines in the file. To do this you first have to know how many lines the file contains, then you have to pick one.

The easiest and sleaziest way to do this is to read the whole file into RAM, split the lines, and do the rest. This should work.

const fs = require('fs')
...
var data = fs.readFileSync('proxies.txt', 'utf8')

const readMe = data.split(/\r?\n/) 
const lineCount = readMe.length
const randomLineNumber = Math.floor(Math.random() * lineCount)
const randomLine = readMe[randomLineNumber]

This is an awful horrible no-good solution if your file contains many lines. It wastes RAM and readFileSync() will slow down your whole app. But if your file contains just a kilobyte or two, practically speaking, it's just fine.

  •  Tags:  
  • Related