5

So I have a public folder directory set up with express and node.

So something like this works fine -

var testImage = new Image();

testImage.src = '/images/png/avatar.png';

But the thing is I have a bunch of pictures inside the png folder that I want to get.

How could I go about doing something like

var imageFolder = new Folder();
var imageList = [];
imageFolder.src = '/images/png';

for(var image in imageFolder){
    imageList.push(imageFolder[image])
}
joe
  • 1,563
  • 4
  • 16
  • 35
  • Possible duplicate of [getting all filenames in a directory with node.js](http://stackoverflow.com/questions/2727167/getting-all-filenames-in-a-directory-with-node-js) – Ruslan Osmanov May 08 '16 at 18:34
  • 1
    That would be on the server side, I'm trying to access them on the client side so there's no filesystem – joe May 08 '16 at 18:36
  • 1
    You can't list a server directory on the front-end, you have to list files on back-end, return them as JSON to the front-end and from there you can work. – Nick Messing May 08 '16 at 18:38

1 Answers1

-2

You can use fs.readdir to read the directory, your example would be:

Async (recommended):

var fs = require('fs')
fs.readdir('/images/png', function (err, images) {
  if (err) {
    return console.error(err)
  }
  var imageList = []
  images.forEach(function (image) {
    var imageObject = new Image()
    imageObject.src = '/images/png/' + image
    imageList.push(imageObject)
  })
})

Sync:

var fs = require('fs')
var images = fs.readdirSync('/images/png')
var imageList = []
images.forEach(function (image) {
  var imageObject = new Image()
  imageObject.src = '/images/png/' + image
  imageList.push(imageObject)
})
Nick Messing
  • 494
  • 5
  • 14