Here is a snippet of an inline <script>
in my HTML
<script>
var fs = require('fs');
var images = fs.readdirSync('/i/cats/');
</script>
I host my website at 000webhost (free version)
My problem is this throws a ReferenceError, require is not defined
To be clear, I am trying to find the files on the server, not on the client.
EDIT JavaScript in html is client-side, so require doesn't work. Therefor i have to use PHP, here is what i got so far:
<?php
$images = array();
if ($handle = opendir('/i/cats')) {
while (false !== ($entry = readdir($handle))) {
array $images = array_push(array $images, $entry);
}
closedir($handle);
}
?>
It seems like it take the directory from the root of the server. How can i fix this?
Javascript is one of the few languages that runs both back-end and front-end. This can be confusing, because some tutorials will provide code for the back-end (node.js).
While it can run back-end, most webhosts don't provide that option. Even if they do, you would have to read up on the difference before you can combine that with front-end javascript.
What you are currently trying to do, is run server-side code on the client-side (webbrowser).
To run this properly, install node.js on your PC and run the script with node (node script.js
).
This cannot work if you host your files on an apache webserver. 000webhost provides apache. Use PHP instead if you really want this.