LoginSignup
1
0

More than 5 years have passed since last update.

Emscripten File System API でディレクトリツリーを表示する

Posted at

Emscripten File System API でディレクトリツリーを表示する

大本営 にはごく一部のAPIしか載っていないのでソースコードを読むかコンソールで FS に生えているメソッドを確認する必要がある。

コード

function ls(pathname){
  var names = FS.readdir(pathname);
  return names.map(function(name){
    var stat = FS.lstat(pathname +"/"+ name);
    return {name: name, stat: stat};
  });
}

function getFileType({mode}){
  return FS.isFile(mode) ? "file"
       : FS.isDir(mode) ? "dir"
       : FS.isBlkdev(mode) ? "blcdev"
       : FS.isChrdev(mode) ? "chardev"
       : FS.isLink(mode) ? "symlink"
       : FS.isFIFO(mode) ? "fifo"
       : FS.isSocket(mode) ? "socket"
       : "unkown";
}

function tree(pathname){
  var elms = ls(pathname).map(function(elm){
    if(elm.name !== "." && elm.name !== ".." && getFileType(elm.stat) === "dir"){
      var dir = tree(pathname +"/"+ elm.name);
      return {name: elm.name, type: dir};
    }
    return {name: elm.name, type: getFileType(elm.stat)};
  });
  return elms.reduce(function(o, elm){
    o[elm.name] = elm.type;
    return o;
  }, {});
}


FS.chdir("/home/web_user");
FS.mkdir('working');
FS.mount(MEMFS, { root: '.' }, 'working');
FS.chdir("working");

console.log(JSON.stringify(tree("/home"), null, "  "));

結果

{
  ".": "dir",
  "..": "dir",
  "web_user": {
    ".": "dir",
    "..": "dir",
    "working": {
      ".": "dir",
      "..": "dir"
    }
  }
}

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0