Jump to content

Pick random image from folder in NodeJS?

Go to solution Solved by jincio,

You could use the native library 'fs'. and use a method of that library that is readdirSync()

var fs = require('fs');
var files = fs.readdirSync('/path/to/dir/')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)] 

the discord part seems correct, only that you need to change the path to the image to

'/path/to/image/' + chosenFile

P.S. you could use the variable '__dirname' which is the path of the current module so for example if your .js is in '/home/user/Project/discord-bot/app.js' and you need the image in '/home/user/Project/discord-bot/images/image.jpg' you can just write __dirname + '/images/image.jpg'

So I wanted to program a discord bot that responds with a random image from a folder on my computer.

This is the code

 

https://hastebin.com/jamopagico.js

 

The code runs nodejs and in order for it to respond with an image, I tried to make it do the following:

 

1. Use math.random to print out random number, in range from 1 to the maximum number of images in the folder. 

var foldercount = ls -1 /home/babadoctor/imagefolder/rei/ | wc -l
var temp = Math.floor(Math.random() * Math.floor(foldercount));

2. Use the random number to pick a random image in the directory (i have absolutely no idea how to do this, i tried doing it with temp.jpg , temp being the image number, not the name of the image (??????))

 

Can anyone help me out here? I have absolutely no idea how to do this.

 

OFF TOPIC: I suggest every poll from now on to have "**CK EA" option instead of "Other"

Link to comment
https://linustechtips.com/topic/949042-pick-random-image-from-folder-in-nodejs/
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

You could use the native library 'fs'. and use a method of that library that is readdirSync()

var fs = require('fs');
var files = fs.readdirSync('/path/to/dir/')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)] 

the discord part seems correct, only that you need to change the path to the image to

'/path/to/image/' + chosenFile

P.S. you could use the variable '__dirname' which is the path of the current module so for example if your .js is in '/home/user/Project/discord-bot/app.js' and you need the image in '/home/user/Project/discord-bot/images/image.jpg' you can just write __dirname + '/images/image.jpg'

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×