Serve a random static file with Express

Share this video with your friends

Social Share Links

Send Tweet

In this lesson we will look at serving static files using the static helper provided by Express.

We'll then use the file system module in Node to read the contents of our static directory, select a random file and send the path back to our client.

Kevin Cunningham: [0:01] My API is serving a single URL that's hard coded. I can update and change. I want to be able to serve files from my public folder here. I've got some images collected already. What I am going to do is I'm going to use an Express helper. I'm going to do app.use. I won't do this on my [inaudible] route.

[0:28] I want express.static, and the folder I care about is public. Now, I can navigate to port 3001/image1.jpg, and here is one of the images that I have.

[0:43] What I would like today is instead of getting Bill Murray and this hard-coded URL, I would like to get a random image from this directory. The first thing I'd like to do, because I'm going to access something from the file system to select a random file, I'm going to use the file system library from Node.

[1:06] I need to know what my BASE_URL is, and in this case, I'm going to hard code that as my localhost:3001. That's where my API is and my imageDirectory, which is /public.

[1:25] On my images route I want to in some way return a random image. How about we have a function, which is called randomImage() and all that does is return a string. In this case, if I just move string there, and instead have randomImage, nothing should have changed, change this to 200/400, and we've got a new image, cool.

[2:12] We need to get a string that's representing the image in our public folder. How are we going to do that? First of all, I'm going to get all the files in that directory. I'm going to use the fs method, readdirSync(), and I'm going to use the __dirname, which gets my directory and then the imageDirectory, which we've defined above.

[2:40] Then, I'm going to choose a file. My chosen file is going to be files, which is an array. I want the Math.floor of...What I want, I want Math. I want a random file somewhere based on the files.length. Instead of returning Phil Murray, I want to return the BASE_URL. I'm using template [inaudible] , and then /${chosenFile}.

[3:18] Hopefully now, when I press my Get new image, I'll get one of the images from my directory.