我试图使用Node.js获取目录中所有文件的名称列表。我希望输出文件名数组。我该怎么做?


当前回答

我通常使用:FS Extra。

const fileNameArray = Fse.readdir('/some/path');

结果:

[
  "b7c8a93c-45b3-4de8-b9b5-a0bf28fb986e.jpg",
  "daeb1c5b-809f-4434-8fd9-410140789933.jpg"
]

其他回答

它只有2行代码:

fs=require('fs')
fs.readdir("./img/", (err,filename)=>console.log(filename))

图像:

IMO完成此类任务最方便的方法是使用glob工具。这是node.js的glob包

npm install glob

然后使用通配符匹配文件名(示例取自软件包的网站)

var glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
})

如果您计划使用globby,这里有一个示例来查找当前文件夹下的任何xml文件

var globby = require('globby');

const paths = await globby("**/*.xml");  

使用npm列表内容模块。它读取给定目录的内容和子内容,并返回文件和文件夹路径列表。

const list = require('list-contents');

list("./dist",(o)=>{
  if(o.error) throw o.error;
   console.log('Folders: ', o.dirs);
   console.log('Files: ', o.files);
});

试试这个,它对我有用

import fs from "fs/promises";

const path = "path/to/folder";

export const readDir = async function readDir(path) {

    const files = await fs.readdir(path);

    // array of file names
    console.log(files);
}

从Node v10.10.0开始,可以将fs.readdir和fs.readderSync的新withFileTypes选项与dirent.isDirectory()函数结合使用,以过滤目录中的文件名。看起来像这样:

fs.readdirSync('./dirpath', {withFileTypes: true})
.filter(item => !item.isDirectory())
.map(item => item.name)

返回的数组的格式为:

['file1.txt', 'file2.txt', 'file3.txt']