Randomly choose files in Nodejs

Asked

Viewed 240 times

1

I’m trying to create a bot for Twitter/Facebook/Discord that reads a pair of files randomly in a certain folder to post on networks.

Basically in the folder there will be several JPG or PNG images, and for each image there will be a JSON with the same name (and obviously different extension) that will contain some features for posting. Then the script will choose an image randomly, consume the JSON that makes pair with it and so will be posted the image on social networks.

How this function could be done?

  • 1

    An idea to start is to make a vector with the names of the JPG/PNG files programmatically, and then make a function to generate an Rand from 0 to n -1 and then catch the . json of vector image[random]

  • @IWHKYB Good idea, but how could I do it?

  • Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!

3 answers

0

Use the function fs.readdirSync to read the contents of the directory and Filtre by the file extension. After this select a random record with the function Math.random together with the Math.floor:

const { readdirSync, readFileSync } = require('fs');
const { join } = require('path');
const pasta = './imagens';

const selecionar = () => {
  // Seleciona os nomes de arquivos que são JPG ou PNG
  const arquivos = fs.readdirSync('${pasta}').filter((nome) => nome.indexOf('.jpg') !== -1 || nome.indexOf('.png'));
  // Seleciona um arquivo aleatoriamente
  const selecionado = arquivos[Math.floor(Math.random() * arquivos.length)];
  // Busca o arquivo de informações
  const informacoes = join(pasta, selecionado.replace('.jpg', '.json').replace('.png', '.json'));

  return JSON.parse(informacoes);
};

0

You can also create a function that does this all asynchronously, using callbacks:

const fs = require('fs')
const path = require('path')

function getRandomImageData(dir, callback) {
  fs.readdir(dir, (err, files) => {
    if (err) callback(err, null)

    // Filtra os arquivos com extensão ".json":
    const imgFiles = files.filter((name) => path.extname(name) !== '.json')

    // Seleciona uma imagem aleatória:
    const randomImg = imgFiles[Math.floor(Math.random() * imgFiles.length)]
    const { name: randomImgName } = path.parse(randomImg)

    // Captura os dados da imagem selecionada:
    const randomImgData = files.find((file) => file === `${randomImgName}.json`)

    // Cria um objeto com todos os dados:
    const imgData = {
      imgName: randomImg,
      imgData: randomImgData
    }

    // Invoca o callback:
    callback(null, imgData)
  })
}

// Está acessando o diretório "data":
getRandomImageData('./data', (err, data) => {
  if (err) {
    throw err
  }

  // Faça o que desejar. O objeto "data" contém o nome de uma imagem escolhida
  // de forma aleatória e o arquivo .json correspondente.
  console.log(data)
})

Basically, the linear functioning of the function occurs as follows:

  1. We create a function that accepts as the first argument the directory name containing the images and files .json;
  2. Through the fs.readdir, we access all the files in the directory;
  3. We have deleted all directories with the extension .json;
  4. From the remaining files, we chose a random image;
  5. Based on the chosen image, we recovered the file .json for the chosen image;
  6. We invoke the callback past, providing an object with the name of the image and its file .json.

To learn more, read the comments in the code.

Reference:

0

I put here as an answer to make reading easier

To see the list of files in the folder you can use Fs.readdir.:

const folder = './foldername/';
const fs = require('fs');
const files_arr;

fs.readdir(folder, (err, files) => {
    files_arr = files
});

with the file array, I believe that if there are . jpg, . png and . json in the same printer, it would be good to filter to take the . json from that list (giving a split by char '.')

filtered_files = filter(files_arr, funcao_de_filter_here);

then check the size of this array and make a random of 0 to size - 1 and select the file by changing the extension to . json

Browser other questions tagged

You are not signed in. Login or sign up in order to post.