Have you ever needed to create a bunch of random file names to test something like Regular Expression? Well, recently I did, and I didn’t have a collection of files to hand that would test the regular expression in the way I required.

So what do programmers do when they have a need? They fill a need, to paraphrase from the animated film Robots. We are going to write a script that creates a chosen number of random file names. We’ll allow it to select from an approved list of extensions, and a collection of words to make it look like actual file names.

Why do I need random file names?

This creates file names that will realistically match the ones that will appear in a live environment. Having better data to begin with will improve your code because it will allow you to deal with unexpected file names that you might not have tested normally. This will allow you to put code to handle these issues at dev time is always better than just before making a project live.

Getting started

As I’ve written a lot of front end test in CodePen, I thought I’d use it to quickly run this simple JavaScript to generate everything I needed.

All of this code is available at the bottom of this page in an embedded codepen.

Extensions

The first thing you’ll need to decide on your sources. By this, I mean compile a list of file extensions. We’ll start by setting a variable to tell it how many files we want to create, and then an array of extensions to use.

let fileCount = 10;
let fileExtensions = [
'bmp','jpg','jpeg','gif','png','psd','eps',
'doc','docx','pdf','xls','xlsx','txt',
'zip','bat','exe'
];

You’ll notice that my list of extensions contain many file types you would expect to be uploaded to a website. Add to yours or reduce to suit your needs.

File name source

To make our file names realistic, I decided to use actual text. This way, it’s more likely that the file names are going to better represent file names you’ll get in the real world. You can use file_01.jpg, file_02.jpg, file_03.jpg and so on. But I think this only tests your code in a controlled environment, and can be restrictive.

A tool I turn to for filler text all the time is Fillerama. It generates filler text as an alternative to Lorem Ipsum, which I find boring, and doesn’t look anything like actual text when comparing two designs side by side. Fillerama is something I’ve spoken about before in previous blogs over at BarkWeb.

My personal favourite is the Star Wars text, but you can pick from Doctor Who, The Simpsons, Futurama and a lot more. Head on over there, and grab a few paragraphs of text. I normally untick all the headers, lists and inline styles. Then wrap the text in quotes and assign to a variable like in my example below.

let fileWords = "Oh God, my uncle How am I ever gonna explain this The plans you refer to will soon be back in our hands I want to come with you to Alderaan There's nothing for me here now I want to learn the ways of the Force and be a Jedi, like my father before me Look, I ain't in this for your revolution, and I'm not in it for you, Princess I expect to be well paid I'm in it for the money What! What! Your eyes can deceive you Don't trust them What good is a reward if you ain't around to use it Besides, attacking that battle station ain't my idea of courage It's more likeā€¦suicide You're all clear, kid Let's blow this thing and go home! Don't underestimate the Force I have traced the Rebel spies to her Now she is my only link to finding their secret base I need your help, Luke She needs your help I'm getting too old for this sort of thing";

Preparing for output

We’ll now need to create somewhere to display our output, so in HTML, create a div and give it an ID.


<div id="fileList"></div>

If you want to do this purely in the console, then you can strip out all the formatting I use to create an unordered list in this example and just console.log() the results instead.

Back to the javascript, and just to finish off this section, we want to get the word ready and get the <div> we just created ready.

fileWords = fileWords.split(' ');
let fileList = document.createElement('div')

This takes the paragraph of text we set earlier, and splits it into an array using the spaces. The reason for this is so that we can easily count how many words there are, and then pick one at random to start from. This is an easy way to give us a collection of English words for our file names. But because they are from a paragraph, we can loop through each word, for as many as we need. Then they’ll at least look like actual file names.

Create files

Now we are at a stage where we can start looping through and creating the required number of files. We’ll use the fileCount variable that we created earlier to form our loop.

for (i = 0; i &lt; fileCount; i++) {
//
}

Change the variable we set at the beginning to equal however many files you would like to output.

Creating the file

Now we start to bring it all together.

Selecting file type

Next we are going to randomly select one of our file extensions from our list created earlier. We’ll use the Math.random() function to pick a number at random.

for (i = 0; i &lt; fileCount; i++) {
  let fileExtension = fileExtensions[Math.floor(Math.random() * (fileExtensions.length - 1))];
}

Creating the file name

Next we need to decide how many words are going to be in our file name. We’ll use the same random method above to decide this number.

for (i = 0; i &lt; fileCount; i++) {
  let fileExtension = fileExtensions[Math.floor(Math.random() * (fileExtensions.length - 1))];

  let fileNameLength = Math.floor((Math.random() * 7) + 1);
}

Once we have this bit of information, we’ll loop through selecting words from our array until we reach our randomly chosen target, adding them to the file name. We also add back in the space between each one. The following code should be placed inside the fileCount loop, just under the fileNameLength variable.


  let fileName = '';
  for (n = 0; n &lt; fileNameLength; n++) {
    fileName += fileWords[Math.floor(Math.random() * (fileWords.length - 1))];
    fileName += ' ';
  }

Putting it all together

Finally, we’ll trim the trailing space off, create a list element to display, and add on the period and file extension before appending the name to the unordered list.


  let listItem = document.createElement('li')
  listItem.innerHTML = fileName.trim() + '.' + fileExtension;
  fileList.appendChild(listItem);

Again, the above code should be placed in the fileCount loop.

Display everything

If you are copying our example, and displaying to a web page instead of a console, then the last bit of code, placed after the fileCount loop, should append the list items to the display.


let container = document.getElementById('fileList');
container.appendChild(fileList);

Demo

Here is a copy of the complete code running on CodePen.io.

See the Pen Auto file name generator by Dean Pugh (@wezlar) on CodePen.0

And that completes our code. You should now be able to run this script and it produce the number of file names specified in the variable at the beginning of this article.

Conclusion

Hopefully, the only modifications that you should have to make, are to change the extention list to something more suitable to your requirements. You can also change the text to match something that might make better file names for yourself.

Tags: , , ,

Join the conversation...

Your email address will not be published. Required fields are marked *