Reputation: 856
A pure newbie in javascript :)
What I need is a function to get all the file names in a directory(lets call it results) which is in the same place with my html file.
The function could return array that holds file names or the result could be stored in a global variable.
Regards!
Edit Thanks everyone for the answers and information. I really did not know that I had to use a client side language :)
Upvotes: 0
Views: 3403
Reputation: 5161
What you are trying to do is accessing the directory using JavaScript. Probably you have done so in a server-side language before (Java, Python etc..).
But this is not possible in JavaScript or better to say JavaScript doesn't allow this.
The reason for this is simple. The Javascript runs on your browser and just imagine if I can write a code that runs on your browser and accesses your directories. I could literally read everything on your computer.
Its absurd. Isn't it ? So its simply not possible.
Update: While writing the above answer, I didn't account for server side javascript using Node.js and only focused on javascript on browser. In case, you are using javascript on the server-side then YES, the FileReader module from Node should allow you that.
Though its a 2 year old answer but still Thanks @SQB for pointing that out.
Upvotes: 1
Reputation: 1792
I saw a node answer; here's what you can do in PHP;
Create a new file called 'files.php' and put the following code in there:
<?php
// Specify the directory to scan for files
$dir = '/';
// Store the scandir results in a variable
$files = scandir($dir);
// Encode the array in JSON and echo it
echo json_encode($files);
?>
Save it and upload it to the directory you want to return the files from, make sure you specify the file path (you can modify the $dir with the path needed);
Now you can use JQuery for example to create a GET request to the files.php file we created and return the data back to the client,
<script>
$.get( "files.php", function( data ) {
console.log(data);
});
</script>
You'll see in the console the returned JSON containing all the file names from the result of the scandir; you can use these now to push into your UI, etc.
Upvotes: 1