如何使用node.js获取具有特定文件扩展名的文件列表? [英] How do I get a list of files with specific file extension using node.js?

查看:68
本文介绍了如何使用node.js获取具有特定文件扩展名的文件列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The node fs package has the following methods to list a directory:

fs.readdir(path,[callback])异步readdir(3).读取目录的内容.回调获取两个参数(err,文件)其中files是目录中文件名的数组不包括."和"..".

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)同步readdir(3).返回一个数组不含."的文件名和'..

fs.readdirSync(path) Synchronous readdir(3). Returns an array of filenames excluding '.' and '..

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

But how do I get a list of files matching a file specification, for example *.txt?

推荐答案

您可以使用扩展程序提取器功能过滤文件数组.如果您不想编写自己的字符串操作逻辑或正则表达式,则 path 模块提供了一种这样的功能.

You could filter they array of files with an extension extractor function. The path module provides one such function, if you don't want to write your own string manipulation logic or regex.

var path = require('path');

var EXTENSION = '.txt';

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

编辑根据@ arboreal84的建议,您可能需要考虑诸如 myfile.TXT 之类的情况,这种情况并不太常见.我只是自己测试过, path.extname 不会为您做小写.

EDIT As per @arboreal84's suggestion, you may want to consider cases such as myfile.TXT, not too uncommon. I just tested it myself and path.extname does not do lowercasing for you.

这篇关于如何使用node.js获取具有特定文件扩展名的文件列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆