2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

相対パスをルートパスに変換する

2
Last updated at Posted at 2012-05-25

WebWorkerでは相対パスが効かない。

例えば /hoge/fuga/index.html から WebWorker を通じて ./data.txt を読み込もうとすると /data.txt を読み込もうとして、そんなファイルは無いと怒られてしまう。

あらかじめルートパスに変換してから WebWorker に渡してやると良い。

relpath2rootpath.js
function relpath2rootpath(relpath) {
    if (/^https?:\/\//.test(relpath)) {
        return relpath;
    } else {
        var rootpath = location.pathname;
        rootpath = rootpath.substr(0, rootpath.lastIndexOf("/"));
        rootpath = rootpath.split("/").filter(function(x) {
            return x !== "";
        });
        relpath = relpath.split("/");
        for (var i = 0; i < relpath.length; i++) {
            if (relpath[i] === "..") {
                rootpath.pop();
            } else if (relpath[i] !== ".") {
                rootpath.push(relpath[i]);
            }
        }
        return "/" + rootpath.join("/");
    }
}
2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?