【发布时间】:2014-02-14 16:12:58
【问题描述】:
【问题讨论】:
标签: node.js
【问题讨论】:
标签: node.js
如果您不想在项目中添加新的依赖项(例如 glob),您可以使用普通的 js/node 函数,例如:
var files = fs.readdirSync('C:/tmp').filter(fn => fn.endsWith('.csv'));
Regex 可能有助于进行更复杂的比较
【讨论】:
readdirSync() 并解析结果。但在大多数情况下,单行解决方案比在项目中添加新的依赖项更快
这不被 Node 核心覆盖。您可以查看this module 了解您的需求。
npm i 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.
})
【讨论】:
如果 glob 不是你想要的,或者有点混乱,还有glob-fs。该文档通过示例涵盖了许多使用场景。
// sync
var files = glob.readdirSync('*.js', {});
// async
glob.readdir('*.js', function(err, files) {
console.log(files);
});
// stream
glob.readdirStream('*.js', {})
.on('data', function(file) {
console.log(file);
});
// promise
glob.readdirPromise('*.js')
.then(function(files) {
console.log(file);
});
【讨论】:
以防万一您想通过正则表达式搜索文件(用于复杂匹配),然后考虑使用file-regex,它支持递归搜索和并发控制(以获得更快的结果)。
示例用法
import FindFiles from 'file-regex'
// This will find all the files with extension .js
// in the given directory
const result = await FindFiles(__dirname, /\.js$/);
console.log(result)
【讨论】:
开箱即用的match 非常简单
import fs from 'fs'
fs.readdirSync('C:/tmp/').filter((allFilesPaths:string) =>
allFilesPaths.match(/\.csv$/) !== null)
【讨论】:
不要重新发明轮子,如果您使用 *nix,ls 工具可以轻松做到这一点 (node api docs)
var options = {
cwd: process.cwd(),
}
require('child_process')
.exec('ls -1 *.csv', options, function(err, stdout, stderr){
if(err){ console.log(stderr); throw err };
// remove any trailing newline, otherwise last element will be "":
stdout = stdout.replace(/\n$/, '');
var files = stdout.split('\n');
});
【讨论】:
dir /B 命令尝试类似的结果,您可能还需要在 \r\n 上拆分,不是肯定的
glob 或其他一些模块会更可取(例如,如果您想跨多个平台部署并且不确定ls 的行为是否相同,)但我不认为我的回答草率或“明显或危险地不正确”。 "Use your downvotes whenever you encounter an egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect."