node.js - Nodejs:搜索包含特定单词的文件夹
问题描述
我正在做一个项目,想要搜索并显示包含特定单词的所有文件夹的列表(不区分大小写)。我只想搜索和显示文件夹,而不是其中的内容或任何其他文件。我怎样才能做到这一点?我试过这样做,但无法弄清楚。
这是我的代码:
router.get('/displayDirectories', (req, res) => {
const fs = require("fs");
const userID = req.query.id;
fs.access(`C:/Traning/${userID}`, function(err) {
if(!err)
{
console.log("Directory exists");
//this only prints if I enter the exact full name of the folder
//I also want to add those directories in an array
}
else
{
console.log("Directory does not exist");
}
})
});
任何帮助,将不胜感激。
解决方案
你的问题对我来说听起来不是很清楚(特别是如果你正在寻找一个或多个文件),但关于我的理解,我希望能帮助你
const { readdir } = require("fs");
const { join } = require('path')
router.get('/displayDirectories', (req, res) => {
const userID = req.query.id;
const thePath = join('C:/Traning', userID)
readdir(thePath, (e,d) => {
if(e) {
console.log('err parsing the directory: ', e)
return
}
else {
const list = []
// set all file's name to lowercase
const fileLowerCase = d.map(f => f.toLowerCase())
const files = new Set(fileLowerCase)
// if many files(userIdx) to check: iterate them
// lowercase the researched file for case insensitive
if (files.has(userId.toLowerCase()) === true) list.push(userId)
// another check for ex
if (files.has(userId2.toLowerCase()) === true) list.push(userId2)
if(list.length === 0) console.log('directories does not exist')
else console.log('the matched directories are: ',list)
}
})
});
第一个解决方案的问题是匹配文件的列表(在列表数组中)将是小写的。第二个问题是 Set 对象应该获得唯一的值,但是使用 .toLowerCase() 我们不再确定。
请参阅解决这两个问题的第二个解决方案。
const { readdir } = require("fs");
const { join } = require('path')
router.get('/displayDirectories', (req, res) => {
const userID = req.query.id;
const thePath = join('C:/Traning', userID)
readdir(thePath, (e,d) => {
if(e) {
console.log('err parsing the directory: ', e)
return
}
else {
// set all file's name to lowercase & match them to the target
const list = d.map((f,i) => {
if(f.toLowerCase() === userID.toLowerCase()) return f
})
if(list.length === 0) console.log('directories does not exist')
else console.log('the matched directories are: ',list)
}
})
});
推荐阅读
- reactjs - 将材质ui功能组件迷你变体抽屉转换为类组件Reactjs
- python - 如何以编程方式告知 AWS Step Function 执行已完成?
- jquery - 使用 jQuery 进行模态和事件处理
- android - Ionic FCM 通知自定义声音在 android 7 中有效,但在其他系统中无效
- python - Python:如何将此字符 \ 放在字符串的末尾
- angular - 显示css类更改后初始化组件
- javascript - 将随机数添加到脚本标记
- assembly - 我需要比较双字数
- firebase - 在 GitHub 上创建新存储库时,我应该隐藏我的 firebase(或其他后端)代码的哪些部分?
- java - 无法将数据发送到 mysql 以检索我的 api 中的列表列 [spring data + angular + mysql]