Get all files within a folder containing string, push filenames to array and return array using Node FS
You should ditch callback syntax and use fs.promises Api. This looks much cleaner
const fs = require("fs").promises;
const path = require("path");
const dirname = path.resolve("./results/");
async function readDir(dirname) {
const allResults = [];
try {
const files = await fs.readdir(dirname);
for (const fileName of files) {
try {
const content = await fs.readFile(`${dirname}/${fileName}`, {
encoding: "utf-8"
});
if (content.includes("content string")) {
allResults.push(fileName);
}
} catch (error) {
console.log(error.message);
}
}
return allResults;
} catch (error) {
console.log(error);
}
}
readDir(dirname).then(data => {
console.log(data);
});
Getting all the file names in a specific directory using Javascript
I saw a node answer; here's what you can do in PHP;
Create a new file called 'files.php' and put the following code in there:
<?php
// Specify the directory to scan for files
$dir = '/';
// Store the scandir results in a variable
$files = scandir($dir);
// Encode the array in JSON and echo it
echo json_encode($files);
?>
Save it and upload it to the directory you want to return the files from, make sure you specify the file path (you can modify the $dir with the path needed);
Now you can use JQuery for example to create a GET request to the files.php file we created and return the data back to the client,
<script>
$.get( "files.php", function( data ) {
console.log(data);
});
</script>
You'll see in the console the returned JSON containing all the file names from the result of the scandir; you can use these now to push into your UI, etc.
Related Topics
The Use of the Triple Exclamation Mark
How to Save Binary Buffer to Png File in Nodejs
Hide Menu Sidebar When Clicking Outside the Bar or the Button
How to Make a Bot React to Its Own Message
How to Delete a Localstorage Item When the Browser Window/Tab Is Closed
Group By, and Sum, and Generate an Object for Each Array in JavaScript
Checking for Null Is Not Working for Ajax Json Data
Json Object Array Inside Array Find and Replace in JavaScript
Re-Render Same Component on Url Change in React
How to Get the Value by a Key from a Super Nested Json
How to Simulate Key Press Events Programmatically
Javascript: Location.Href to Open in New Window/Tab
How to Vertically and Horizontally Center a Component in React
Check If Current Time Is Between Two Given Times in JavaScript
How to Apply CSS to Parent Using Child Selector - With CSS or Angular 2
How to Display an Image from an Array of Images in React