'Loop recursive inside a folder using Emscripten File API
How to loop files inside a folder using Emscripten?
E.g., I've created data a folder '/res'
(FS.mkdir('/res')
) and some data temp files and subfolders inside the '/res'
.
How can I loop files and folders inside?
I've just found FS.isDir()
. but no more.
What is the proper way to extract the data (file names):
/res/file1.txt
/res/file2.txt
/res/file2.txt
/res/dir/file01.txt
/res/dir/file02.txt
etc.
Solution 1:[1]
FS.readdir
lists all names (files and folders) of a directory, but not recursively. You can use FS.lookupPath
, FS.isFile
and FS.isDir
to recursively crawl the filesystem.
function fsReadAllFiles(folder) {
const files = [];
function impl(curFolder) {
for (const name of FS.readdir(curFolder)) {
if (name === '.' || name === '..') continue;
const path = `${curFolder}/${name}`;
const { mode, timestamp } = FS.lookupPath(path).node;
if (FS.isFile(mode)) {
files.push({path, timestamp});
} else if (FS.isDir(mode)) {
impl(path);
}
}
}
impl(folder);
return files;
}
Note, this probably breaks for symlinks, but that should be a simple addition.
Solution 2:[2]
FS.readdir()
returns childs of directory.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Connor Clark |
Solution 2 | Community |