Reading filenames from a folder (SOLVED)

Hello. I've known of these forums since RPG VX, and they've been greatly usefull for past projects. This time, however, I have been unable to figure it out, so I'm posting a question for the first time.

This is the situation. Let's say I have an "Albums" folder in the project directory (where you find the audio, data, img folders). There, I have an unspecified number of files. The question is, how can I know the filename of the file on the <i>th position in that folder (if they are alphabetically ordered)?

Thank you very much for your comments.
The first place to start looking is the documentation for the "file system" module.
https://nodejs.org/docs/latest-v10.x/api/fs.html

You want to read the directory, so you can use this function specifically.
https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_fs_readdir_path_options_callback

The callback will give an array of filenames, so you can use that to access the i'th file.
I'm sorry if this is an inadequate follow up question, but, would that mean I'm looking for something like this?

var filenames = new Array(fs.readdir('/folder', function (err, files) {
if (err) {
}
console.log(files);
}); );
var wantedfilename = filenames;

Where wantedfilename is the filename of the i'th file in folder.
If you can use CODE tags, that'll help show the formatting better 🙂

I linked the documentation because I didn't know how familiar you were with coding and JS.

To access the i-th element of an array, you use square brackets and the index. Learn more about arrays here.

The asynchronous version of readdir doesn't return an array, it provides access to the array from the callback.

Code:
var filenames  // make a variable outside the scope of readdir
fs.readdir('/folder', function (err, files) {
   if (err) {
      console.error(err)
   } else {
      filenames = files
      console.log(filenames[2]) // log the 3rd filename
  }
}) 
console.log(filenames) // careful! This will log undefined, because it's asynchronous!

The synchronous readdir returns an array. So you can pick whichever version depending on if you need it to be asynchronous or synchronous.

Code:
var filenames = fs.readdirSync('/folder')
console.log(filenames[2]) // log the third filename
To access the i-th element of an array, you use square brackets and the index.
I actually knew about that! For some reason I forgot to type in

Code:
var wantedfilename = filenames[i]

It doesn't matter, since it wouldn't have worked anyway.

The synchronous readdir returns an array.

So, from what I've understood, I'd have to work something like this:

Code:
var fs = require('fs');
var files = fs.readdirSync('/folder');
var Bgm = {name: files[2].slice(0, -4), volume:80, pitch: 100, pan: 100};
AudioManager.playMe(Bgm);

Which works perfectly! Thank you!

Original thread: https://forums.rpgmakerweb.com/threads/reading-filenames-from-a-folder-solved.114731/