Get List of Filenames in Folder With JavaScript

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



Leave a reply



Submit