For example, if you have some json data in the sample folder and you want to load all of them, how can you describe it?
jquery
If you just want to load it, why don't you do the following?
// The file name here is increasing as much as you need.
const filenames = [
"sample/data.json",
"sample/data2.json"
];
filenames.forEach(function(filename){
$.getJSON(filename, function(data){
console.log (filename, data);
});
});
I've looked it up for the same purpose before and found it wasn't prepared by standard.
I have implemented it.
I rewritten the code (TypeScript) that I had in hand to JavaScript.
I don't have an environment right now, so I haven't checked the operation yet (I hope it works well).
The approach is
First, list all the files in the directory, and then narrow them down with extensions.
import fs from 'fs';
import path from 'path';
constenumFilePaths=(dirPath, extension)=>{
const filePaths=[];
const funds =fs.readdirSync(dirPath);
found.each((found)=>{
const subPath=path.resolve(dirPath, found);
const stat =fs.statSync(subPath);
if(stat.isFile()){
filePaths.push(subPath);
}
});
constfiltered=filePaths.filter((filePath)=>{
const=path.extname(filePath).toLowerCase().replace('.', '');
return ext===extension;
});
return filtered;
};
const jsonFilePaths=enumFilePaths('./sample', 'json');
Turn this jsonFilePaths
in a loop to $.getJSON()
.
With a few modifications, you can increase the number of extensions you're looking for to more than one.
You can also look in a subdirectory.
(Originally, it had that function, but it was omitted when pasting because it was different from your requirements.)
© 2024 OneMinuteCode. All rights reserved.