微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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不会为你做小写.

原文地址:https://www.jb51.cc/js/159463.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐