deno: Get the path of the current script in

In deno obtaining the path of the current script is done via the import.meta.url api:

const scriptPath = new URL(import.meta.url).pathname;

On Windows though this will return a path with unix style path seperators and a leading /:


This cannot be used for example to read the contents of the current script. We'll need a better solution.

Whether or not the script is running on Windows can be detected via the api:

const isWindows = === "windows";

So we can use that to correct the path seperators and remove the leading /:

const isWindows = === "windows";

const scriptPath = new URL(import.meta.url).pathname
  .replaceAll("/", isWindows ? "\\" : "/")
  .substring(isWindows ? 1 : 0);; Deno.readTextFile(scriptPath));