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


当前回答

如果上面的许多选项看起来太复杂,或者不是您想要的,这里是另一种使用node-dir的方法https://github.com/fshost/node-dir

npm install node-dir

下面是一个somple函数,用于列出在子目录中搜索的所有.xml文件

import * as nDir from 'node-dir' ;

listXMLs(rootFolderPath) {
    let xmlFiles ;

    nDir.files(rootFolderPath, function(err, items) {
        xmlFiles = items.filter(i => {
            return path.extname(i) === '.xml' ;
        }) ;
        console.log(xmlFiles) ;       
    });
}

其他回答

采用@湖南罗斯托米扬的一般方法,使其更加简洁,并添加了excludeDirs论点。使用includeDirs进行扩展很简单,只需遵循相同的模式:

import * as fs from 'fs';
import * as path from 'path';

function fileList(dir, excludeDirs?) {
    return fs.readdirSync(dir).reduce(function (list, file) {
        const name = path.join(dir, file);
        if (fs.statSync(name).isDirectory()) {
            if (excludeDirs && excludeDirs.length) {
                excludeDirs = excludeDirs.map(d => path.normalize(d));
                const idx = name.indexOf(path.sep);
                const directory = name.slice(0, idx === -1 ? name.length : idx);
                if (excludeDirs.indexOf(directory) !== -1)
                    return list;
            }
            return list.concat(fileList(name, excludeDirs));
        }
        return list.concat([name]);
    }, []);
}

示例用法:

console.log(fileList('.', ['node_modules', 'typings', 'bower_components']));

加载fs:

const fs = require('fs');

异步读取文件:

fs.readdir('./dir', function (err, files) {
    // "files" is an Array with files names
});

读取文件同步:

var files = fs.readdirSync('./dir');

使用flatMap:

function getFiles(dir) {
  return fs.readdirSync(dir).flatMap((item) => {
    const path = `${dir}/${item}`;
    if (fs.statSync(path).isDirectory()) {
      return getFiles(path);
    }

    return path;
  });
}

给定以下目录:

dist
├── 404.html
├── app-AHOLRMYQ.js
├── img
│   ├── demo.gif
│   └── start.png
├── index.html
└── sw.js

用法:

getFiles("dist")

输出:

[
  'dist/404.html',
  'dist/app-AHOLRMYQ.js',
  'dist/img/demo.gif',
  'dist/img/start.png',
  'dist/index.html'
]

如果有人:

只想列出项目本地子文件夹中的文件名(不包括目录)

✅ 无其他依赖项✅ 1功能✅ 规格化路径(Unix与Windows)

const fs = require("fs");
const path = require("path");

/**
 * @param {string} relativeName "resources/foo/goo"
 * @return {string[]}
 */
const listFileNames = (relativeName) => {
  try {
    const folderPath = path.join(process.cwd(), ...relativeName.split("/"));
    return fs
      .readdirSync(folderPath, { withFileTypes: true })
      .filter((dirent) => dirent.isFile())
      .map((dirent) => dirent.name.split(".")[0]);
  } catch (err) {
    // ...
  }
};

README.md
package.json
resources
 |-- countries
    |-- usa.yaml
    |-- japan.yaml
    |-- gb.yaml
    |-- provinces
       |-- .........


listFileNames("resources/countries") #=> ["usa", "japan", "gb"]

但是,上面的答案不会对目录执行递归搜索。以下是我对递归搜索所做的操作(使用node walk:npm install walk)

var walk    = require('walk');
var files   = [];

// Walker options
var walker  = walk.walk('./test', { followLinks: false });

walker.on('file', function(root, stat, next) {
    // Add this file to the list of files
    files.push(root + '/' + stat.name);
    next();
});

walker.on('end', function() {
    console.log(files);
});