How do you get a list of the names of all files present in a directory in Node.js?
You can use the fs.readdir
or fs.readdirSync
methods. fs
is included in Node.js core, so there's no need to install anything.
fs.readdir
const testFolder = './tests/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
});
fs.readdirSync
const testFolder = './tests/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.
The second is synchronous, it will return the file name array, but it will stop any further execution of your code until the read process ends.
output list of files in a directory by array of extensions
In your filter, couldn't you just do:
let fileNames = rawFileNames.filter(file => {
return extensions.includes(path.extname(file).toLowerCase())
})
I need to retrieve ALL images (regardless of number and name) from a local folder and display them on my website
The basic idea is solid, there are just some details in the execution that need to be cleaned up. I took a swing at setting this up locally and cleaning it up a bit.
PHP:
<?php
/**
* This PHP script returns javascript that feeds an image gallery. A JSON array of images are returned along with a
* parameter that indicated the base URL for the images.
*
*/
/**
* @var $localImageDir string
* The path to the local image directory relative to this script
*/
$localImageDir = 'img';
/**
* @var $baseUrl string
* The URL path to the image directory
*/
$baseUrl = 'http://localhost/img/';
/**
* This function returns an array of image file names in the specified directory. The output is limited
* using the limit parameter
*
* @param string $localImageDir
* @param string $baseUrl
* @param int $limit
* @return array
*/
function returnImages($localImageDir = '.', $baseUrl='', $limit = 5)
{
//valid image extensions
$pattern = "/(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)/";
$files = array();
if ($handle = opendir($localImageDir))
{
while (false !== ($file = readdir($handle)))
{
//Use preg_match here, eregi is deprecated
if (preg_match($pattern, $file))
{
$files[] = $baseUrl.$file;
}
}
closedir($handle);
}
// Limit results
$output = array_slice($files, 0, $limit);
return $output;
}
// Get the image list as an array
$imageArray = returnImages($localImageDir, $baseUrl);
//Encode the image array as JSON
$json = json_encode($imageArray);
//Set the appropriate HTTP header and echo the JavaScript
Header("content-type: application/x-javascript");
echo 'var galleryImages=' . $json.';';
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="images.php"></script>
<script type="text/javascript">
var curImg=0;
function rotateImages()
{
document.getElementById("slideshow").setAttribute("src", galleryImages[curImg]);
curImg=(curImg<galleryImages.length-1)? curImg+1 : 0;
}
window.onload=function()
{
setInterval("rotateImages()", 2500)
}
</script>
</head>
<body>
<div style="width: 170px; height: 160px">
<img id="slideshow" src="pics/bear.gif"/>
</div>
</body>
</html>
In your original script, there were some syntax errors in your for loop - those "i"s need $s. Also, $files(i) should be $files[i]. Beyond that, you're doing a lot of work that you don't need to do, you can simply create an array of file names and use json_encode to format them properly for JavaScript. It's also a good idea to have the base URL to your images set up as a variable in this script rather than in the client. We can send that along with the image data.
You're also using eregi, which is deprecated, I replaced that with preg_replace, which requires a small tweak to your regex.
On the HTML side, I just added correct barebones markup, and changed function and variable names to be a bit more readable, and changed the script to use the variable base URL.
You will need to change the path to the PHP script in the HTML, I just changed it for my local setup.
Good luck.
Related Topics
My Very Simple Greasemonkey Script Is Not Running
Object Method with Es6/Bluebird Promises
Are Loops Really Faster in Reverse
Benefits of Prototypal Inheritance Over Classical
How to Get Evaluated Attributes Inside a Custom Directive
How to Use Underscore.Js as a Template Engine
Which Keycode for Escape Key with Jquery
Making Custom Right-Click Context Menus for My Web-App
How Do Browsers Pause/Change JavaScript When Tab or Window Is Not Active
iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari
A Cors Post Request Works from Plain JavaScript, But Why Not with Jquery
How to Call Loading Function with React Useeffect Only Once
How to Get the Destination Url for the Onbeforeunload Event
Dangerous Implications of Allman Style in JavaScript
Using Variable Keys to Access Values in JavaScript Objects
Get First and Last Date of Current Month with JavaScript or Jquery