need to get the number of images in folder from directory just by javascript.
I searched and tried several ways, but i didn't find any javascript solution.
CodePudding user response:
Using frontend JS is not possible, but using NodeJS it is.
In case you want to achieve it using NodeJS, I wrote an example of reading and retrieving the count of 'png' files in a directory. This is how I achieved it:
1-Build a NodeJS project:
mkdir myProject
cd myProject
npm init -y
2-Write the example:
touch index.js
const fs = require('fs')
const dir = '.'
const fileExtension = 'png'
fs.readdir(dir, (err, files) => {
let count = 0
files.forEach(element => {
if (getFileExtension(element) === fileExtension) {
count
}
})
console.log(count)
})
/**
*
* @param {String} fileName
* @source https://stackoverflow.com/a/12900504
* @returns
*/
const getFileExtension = fileName => {
return fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) 2)
}
3-Execute it:
node index.js
2 // <- output
CodePudding user response:
Use fs. Look at this simple example: In your directory create a file filesCounter.js
, next to the images folder
filesCounter.js
const fs = require("fs");
const folder = "./images_folder";
fs.readdir(folder, (err, images) => {
console.log(images.length);
});
As you can see, just set the path of the folder with the images you want to count in the dir
variable and you're done
Run the script by running node filesCounter.js
.
CodePudding user response:
You can use the fs module in Node.js to read the contents of a directory and count the number of files in it. Here's an example:
const fs = require('fs');
// specify the directory you want to read
const directory = './my-directory';
// read the contents of the directory
fs.readdir(directory, (err, files) => {
if (err) {
// handle error
} else {
// count the number of files in the directory
const numFiles = files.length;
console.log(`There are ${numFiles} files in the directory.`);
}
});
Keep in mind that this code will only work on a server running Node.js, and not in a web browser. If you want to count the number of images on a web page, you can use JavaScript to select all of the elements on the page and then use the length property to get the number of images. Here's an example:
// select all of the images on the page
const images = document.querySelectorAll('img');
// get the number of images
const numImages = images.length;
console.log(`There are ${numImages} images on the page.`);
I hope this helps!