javascript – 如何使用node.js获取具有特定文件扩展名的文件列表?

节点 fs包具有以下列出目录方法

fs.readdir(path,[callback]) Asynchronous readdir(3). Reads the
contents of a directory. The callback gets two arguments (err,files)
where files is an array of the names of the files in the directory
excluding ‘.’ and ‘..’.

fs.readdirsync(path) Synchronous readdir(3). Returns an array of
filenames excluding ‘.’ and ‘..

但是如何获得与文件规范匹配的文件列表,例如* .txt?

解决方法

您可以使用扩展提取功能过滤它们的文件数组.如果您不想编写自己的字符串操作逻辑或正则表达式,则路径模块提供一个此类函数.
var path = require('path');

var EXTENSION = '.txt';

var targetFiles = files.filter(function(file) {
    return path.extname(file).toLowerCase() === EXTENSION;
});

编辑根据@ arboreal84的建议,你可能想要考虑诸如myfile.TXT之类的情况,这并不太常见.我自己测试了它,而path.extname不会为你做小写.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...