Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
How to read a random line from a txt file nodejs

I have a txt file with around 5000 lines in it, I would like to print a random line from that file. I have tried using readline but cant figure out how to choose which line to print using integers. What would be the fastest way to do this without using much memory?

Here is my code

const readline = require("readline");
const fs = require("fs");

const file = readline.createInterface({
    input: fs.createReadStream('file.txt'),
    output: process.stdout,
    terminal: false
});

file.on('line', (line) => {
    console.log(line);
})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The straightforward solution would be:

  1. read file
  2. split by \n, save to array
  3. get number of lines (== length of array)
  4. generate random number between 0 and number of lines
  5. return array[generated_number]

But it might use quite a bit of memory if your file is really large.

so without reading the entire file, off the top of my head - Maybe seek to a random position, then read until you hit \n, and then again read until \n, then split by \n and pick the middle part of the array?

Note- this will break if the last line isn't followed by a new line. (if the random position is in the last two lines)

about 4 years ago · Juan Pablo Isaza Relatório

0

two approaches here:

  1. read all file, choose random number between 1 and 5000 and return that line (not good for general solution)
  2. pre-define random line and return it when getting to that line.
const readline = require("readline");
const fs = require("fs");

const file = readline.createInterface({
    input: fs.createReadStream('file.txt'),
    output: process.stdout,
    terminal: false
});
const radnomLineNumber = getRandomInt(5000);
let i = 0;
file.on('line', (line) => {
   if (randomLineNumber === i) {
      console.log(line);
      return;
   }
   i++;
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda