Home > Mobile >  Search through files in path using only javascript
Search through files in path using only javascript

Time:10-28

I'm coding a webpage that needs to read some data from different csv on a path depending on the country of the user.

the path is something like this:

./csv/m2-2022-10-25_13_45_55_es.csv
      m2-2022-10-25_13_45_56_fr.csv
      m2-2022-10-25_13_46_04_it.csv
      etc

And those files will be replaced regularly, the only that we'll always have is the country code (es, fr, it, etc).

So, what I need is to list all the files on the path to an array, and loop through the array to find if the last characters of the filename are $countryCode ".csv", and there run some code.

But I can't find how, all the solutions I find are using Node.js, but are there a solution using only Javascript (or jQuery)?

Regards!

CodePudding user response:

You cannot use pure Javascript to do that, because if you wanted to search files in your computer only using javascript, it would be a huge security breach. You must use node.js to open files but you can make an API to your nodejs file from your javascript and you can send as a response the content of your file.

Here some links that might help you :

FS : https://nodejs.org/api/fs.html

NodeJS api : https://medium.com/swlh/how-to-create-a-simple-restful-api-in-node-js-ae4bfddea158

CodePudding user response:

You can check a similar question here:

Get list of filenames in folder with Javascript

You can't access to filesystem from the frontend, this it would be a huge security breach, because anyone could access to your filesystem tree. You have to do a function in backend to build the array you want and send it to frontend.

If you create a function in backend file that returns the array of files in the folder, you can call it from the frontend via XMLHttpRequest or Fetch to get the array in frontend and be able to use in your js file.

  • Related