0

Hello I'm trying to read all the files' file paths in a folder and feed that into an Html file using iteration. I'm using Vue and Node to achieve this but I keep getting vue.js:597 [Vue warn]: Error in beforeCreate hook: "ReferenceError: require is not defined". Below is my code for the Javascript in question.

function init() {
    
    new Vue({
        el: '#imgVue',
        data: {
            basePath: 'images/projects/',
            collectionImg: []

        },
        beforeCreate() {
            const fs = require('fs')
            const imageFolder = 'images/projects'

            fs.readdir(imageFolder, (err, files) => {
                files.forEach(file => {
                    collectionImg.push(file)
                })

            })
        }
    })
}
Squanchy
  • 103
  • 1
  • 2
  • 13
  • @thanksd that post you mentioned is related to accesing js functions inside other js files. My question is about the error raised by `require` when trying to use the node core mudule filesystem in a Vue instance an inside a `beforeCreate()` hook. I can't find a connection between the two posts. TY – Squanchy Apr 10 '18 at 18:18
  • If `require` is not defined, my best guess is that you think you are running this code in a node environment, but you're really running it in your browser. – thanksd Apr 10 '18 at 18:21
  • Sounds reasonable, I'll investigate if Vue instances run on the browser. – Squanchy Apr 10 '18 at 18:25
  • Vue instances run on the browser for sure. But you can't call `require` to require the `fs` package in your browser since you're not in a node environment. – thanksd Apr 10 '18 at 18:27
  • Yeah, ok that makes sense. Any recommendations on how to aproach the problem. I need to use `fs` or something similar to read the filepaths inside the folder and then iterate through the filenames for rendering in html `src: fileName`. Will mark as answer. – Squanchy Apr 10 '18 at 18:58
  • I don't agree that the post marked as a duplicate is actually a duplicate. You aren't using webpack and you aren't in a node environment. In that post, the asker can call `require` but the `require` function isn't able to locate the `fs` package. In your case, you can't even call `require` because you are running the code in the browser. You need to either build your code with webpack, or you could use one of the many suggestions given in this post: https://stackoverflow.com/questions/19059580 – thanksd Apr 10 '18 at 20:04

0 Answers0