I’m creating a "Search File" page that lets users enter a string to find some local files (with NodeJS). I want it so the user can type a part of the string and still get results. For example, if they only typed "ha" then all files that contain the string "ha" should be displayed.
Here’s my current code:
app.post("/search", (req, res) => {
//to read all the file names in the directory, returns ["file_01.txt", "file_02.txt"]
const fileNames = fs.readdirSync(__dirname)
const userInput = req.body.userInput;
const subArr = fileNames.filter((str) => str.includes(userInput));
console.log(subArr); //returns empty
res.render("search.ejs");
});
However, if I declare it explicitly:
const abc = ["ab", "bc", "cd"];
const subArr = abc.filter((str) => str.includes(userInput));
console.log(subArr) //returns an array of words that contain the user input, just like I want it to
Why can’t I filter from fileNames but it works with abc? Please help, thank you!
2
Answers
It looks like the filtering is working fine considering that it works with abc…
In my past experience the issue with includes method is that it is case sensitive and i was trying to debug for so long
try to convert both strings to lowercase or uppercase:
also make sure that everything works as expected some might not like it but console.log is my best friend:
Check where the is not doing what it is supposed to do so you can pinpoint the issue
Make sure __dirname is the directory that you looking for
Make sure that fileNames contains files of the said directory and so on…
req.body.userInput
is populated correctly. If you areusing a form to submit the search query, ensure that the form is
configured to send the data properly.
String.includes()
is case-sensitive. If you wantcase-insensitive matching, you might want to convert both the file
names and the user input to lowercase (or uppercase) before
ensures that the search is
case-insensitive.
converts both the file names
and the user input to lowercase for consistent comparison
.