简体   繁体   English

如何通过JavaScript查看本地文件夹中的文件数?

[英]How can I check the number of files in a local folder by JavaScript?

need to get the number of images in folder from directory just by javascript.需要通过 javascript 从目录中获取文件夹中的图像数量。

I searched and tried several ways, but i didn't find any javascript solution.我搜索并尝试了几种方法,但没有找到任何 javascript 解决方案。

Using frontend JS is not possible, but using NodeJS it is.不可能使用前端 JS,但可以使用 NodeJS。

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.如果您想使用 NodeJS 实现它,我写了一个读取和检索目录中“png”文件计数的示例。 This is how I achieved it:这就是我实现它的方式:

1-Build a NodeJS project: 1-构建一个NodeJS项目:

mkdir myProject
cd myProject
npm init -y

2-Write the example: 2-写例子:

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: 3-执行它:

node index.js

2 //  <- output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM