2021年5月27日木曜日

denoでscript自身のpathを取得

scriptファイルのpathから相対Pathでindex.htmlとかcssファイルにアクセスできるようにしたい。
そのためにscript自身のpathを取得する最低限のソースが以下。
import * as path from "https://deno.land/std@0.97.0/path/mod.ts";
function pathResolver(meta: ImportMeta): (p: string) => string {
return (p) => path.fromFileUrl(new URL(p, meta.url));
}
const resolve = pathResolver(import.meta);
function test(pathBefore: string){
const pathAfter = resolve(pathBefore)
console.log('['+pathBefore+'] -> ['+pathAfter+']')
}
test("./data/test.txt")
test("./css.css")
test("/css.css")
実行結果



「./」が無いとうまく整理されないので注意が必要。



下記のページを参考にさせて頂きました。
【Deno】相対パスでファイル操作をするときに気を付けること

0 件のコメント:

コメントを投稿