0

I want to write a simple photos gallery in NuxtJS 3 where I can throw photos in the public/ or assets/ directories, and then generate a static version of the site for deployment.

I am wondering what is the best way to read the content of the assets/ and public/ directories and store them as an array of file-names?

I tried different approaches: With fs.readdirSync and with storing the list to some env var: process.env.STATIC_REFERRAL_DOCS.

Both approaches I could not get to work properly. Any help/hint welcome :)

vincent trest
  • 85
  • 1
  • 8
  • 1
    Reading the directory with `fs` and storing it as an array of paths is the good approach IMO. – kissu Oct 08 '22 at 14:57

1 Answers1

0

I could solve it like this:

<script>
const fs = require('fs')
    
export default {
  data() {
    return {
      fileList: [],
    }
  },

  created() {
    this.getFileList()
  },

  methods: {
    getFileList() {
      try {
        this.fileList = fs.readdirSync('./public/photos')
        console.log('file list: ', this.fileList)
      } catch (error) {
        console.log('Error: ', error)
      }
    },
  },
}
</script>

One remaining problem is that the browser complains about require:

app.vue:2 Uncaught ReferenceError: require is not defined at app.vue:2:1

Any way to get around this?

kissu
  • 40,416
  • 14
  • 65
  • 133
vincent trest
  • 85
  • 1
  • 8
  • 1
    `require` should not be used, and you should favor `import` rather since we're in a modern era now. Meanwhile, `fs` is only a backend package hence not available on the frontend. You would need to use the [server-only side](https://stackoverflow.com/a/69575243/8816585) of Nuxt while fetching those. Indeed, fetching the various files is not something that the browser allows you, but since Nuxt is isomorphic (running code on server initially then on client), it can cause those issues. Here, you code is not working on the client side, hence the message that you have. – kissu Oct 08 '22 at 17:57
  • Thank you :) I replaced require with import and that is all fine. Regarding the other part of your answer, should I put this code into a server middleware? – vincent trest Oct 08 '22 at 18:57
  • 1
    I rather recommend using `NuxtServerInit`. – kissu Oct 08 '22 at 22:17
  • Is it possible to make the list at compile time for a static nuxt? – Alqua Dec 08 '22 at 10:51
  • You have some `build` hooks indeed. – kissu Dec 08 '22 at 13:22