我有这个程序打印给定目录中的文件列表,按文件的扩展名进行筛选。我需要将它更改为一个程序,该程序搜索包含指定字符串(在文件名中)的所有文件,这些文件也在当前目录下由文件扩展名过滤。基本上我需要第一个参数作为文件名而不是目录路径,目录路径应该是当前目录而不是参数。
var fs = require('fs');
var path = require('path');
var dirPath = process.argv[2]; //directory path
var fileType = '.'+process.argv[3]; //file extension
var files = [];
fs.readdir(dirPath, function(err,list){
if(err) throw err;
for(var i=0; i<list.length; i++)
{
if(path.extname(list[i])===fileType)
{
console.log(list[i]); //print the file
files.push(list[i]); //store the file name into the array files
}
}
});
答案 0 :(得分:0)
我建议使用glob包。请参阅:https://github.com/isaacs/node-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.
})
答案 1 :(得分:0)
将 __ dirname 用于当前目录路径
var fs = require('fs');
var path = require('path');
var dirPath = __dirname;//process.argv[2]; //directory path
var fileType = '.'+process.argv[2]; //file extension
var files = [];
fs.readdir(dirPath, function(err,list){
if(err) throw err;
for(var i=0; i<list.length; i++)
{
if(path.extname(list[i])===fileType)
{
console.log(list[i]); //print the file
files.push(list[i]); //store the file name into the array files
}
}
});
答案 2 :(得分:0)
try this code
var fs = require('fs');
var path = require('path');
var filename = '.'+process.argv[1]; //file extension
var fileType = '.'+process.argv[2]; //file extension
var files = [];
fs.readdir(process.cwd(), function(err,list){
if(err) throw err;
for(var i=0; i<list.length; i++)
{
/*user your conditions AND/OR */
if(path.extname(list[i])===fileType && list[i].indexOf(filename) != -1)
{
console.log(list[i]); //print the file
files.push(list[i]); //store the file name into the array files
}
}
});