如何获取Node.js目录中所有文件的名称列表?

JavaScript

斯丁老丝GO

2020-03-14

我正在尝试使用Node.js获取目录中存在的所有文件的名称的列表。我想要的输出是一个文件名数组。我怎样才能做到这一点?

第1573篇《如何获取Node.js目录中所有文件的名称列表?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
DavaidAPro 2020.03.14

我制作了一个节点模块来自动执行此任务:mddir

用法

节点mddir“ ../relative/path/”

要安装:npm install mddir -g

生成当前目录的markdown:mddir

生成任何绝对路径:mddir / absolute / path

要生成相对路径:mddir〜/ Documents / whatever。

md文件在您的工作目录中生成。

当前忽略node_modules和.git文件夹。

故障排除

如果收到错误“ node \ r:没有这样的文件或目录”,则问题是您的操作系统使用不同的行尾,并且如果您未将行尾样式显式设置为Unix,则mddir无法解析它们。这通常会影响Windows,但也会影响Linux的某些版本。必须在mddir npm全局bin文件夹中将行尾设置为Unix样式。

行尾修复

使用以下命令获取npm bin文件夹路径:

npm config get prefix

将CD放入该文件夹

brew安装dos2unix

dos2unix lib / node_modules / mddir / src / mddir.js

这会将行尾转换为Unix而不是Dos

然后正常运行:node mddir“ ../relative/path/”。

示例生成的markdown文件结构“ directoryList.md”

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js
Itachi小卤蛋凯 2020.03.14

这将起作用并将结果存储在test.txt文件中,该文件将存在于同一目录中

  fs.readdirSync(__dirname).forEach(file => {
    fs.appendFileSync("test.txt", file+"\n", function(err){
    })
})
猴子蛋蛋 2020.03.14

盒子外面

如果您希望使用现成的目录结构对象,我强烈建议您检查directory-tree

假设您具有以下结构:

photos
│   june
│   └── windsurf.jpg
└── january
    ├── ski.png
    └── snowboard.jpg
const dirTree = require("directory-tree");
const tree = dirTree("/path/to/photos");

将返回:

{
  path: "photos",
  name: "photos",
  size: 600,
  type: "directory",
  children: [
    {
      path: "photos/june",
      name: "june",
      size: 400,
      type: "directory",
      children: [
        {
          path: "photos/june/windsurf.jpg",
          name: "windsurf.jpg",
          size: 400,
          type: "file",
          extension: ".jpg"
        }
      ]
    },
    {
      path: "photos/january",
      name: "january",
      size: 200,
      type: "directory",
      children: [
        {
          path: "photos/january/ski.png",
          name: "ski.png",
          size: 100,
          type: "file",
          extension: ".png"
        },
        {
          path: "photos/january/snowboard.jpg",
          name: "snowboard.jpg",
          size: 100,
          type: "file",
          extension: ".jpg"
        }
      ]
    }
  ]
}

自订物件

否则,如果要使用自定义设置创建目录树对象,请查看以下代码片段。在此codeandbox上可以看到一个实时示例

// my-script.js
const fs = require("fs");
const path = require("path");

const isDirectory = filePath => fs.statSync(filePath).isDirectory();
const isFile = filePath => fs.statSync(filePath).isFile();

const getDirectoryDetails = filePath => {
  const dirs = fs.readdirSync(filePath);
  return {
    dirs: dirs.filter(name => isDirectory(path.join(filePath, name))),
    files: dirs.filter(name => isFile(path.join(filePath, name)))
  };
};

const getFilesRecursively = (parentPath, currentFolder) => {
  const currentFolderPath = path.join(parentPath, currentFolder);
  let currentDirectoryDetails = getDirectoryDetails(currentFolderPath);

  const final = {
    current_dir: currentFolder,
    dirs: currentDirectoryDetails.dirs.map(dir =>
      getFilesRecursively(currentFolderPath, dir)
    ),
    files: currentDirectoryDetails.files
  };

  return final;
};

const getAllFiles = relativePath => {
  const fullPath = path.join(__dirname, relativePath);
  const parentDirectoryPath = path.dirname(fullPath);
  const leafDirectory = path.basename(fullPath);

  const allFiles = getFilesRecursively(parentDirectoryPath, leafDirectory);
  return allFiles;
};

module.exports = { getAllFiles };

然后,您可以简单地执行以下操作:

// another-file.js 

const { getAllFiles } = require("path/to/my-script");

const allFiles = getAllFiles("/path/to/my-directory");
宝儿Pro 2020.03.14

IMO执行此类任务的最便捷方法是使用全局工具。这是用于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.
})

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android