In Deno, you can use Deno.cwd()
:
const currentWorkingDirectory = Deno.cwd();
console.log(currentWorkingDirectory);
In Node.js, you can use process.cwd()
:
const currentWorkingDirectory = process.cwd();
console.log(currentWorkingDirectory);
In browser client code, you can use location.pathname
:
const pathname = location.pathname;
console.log(pathname);
//Beware that the pathname might not correspond to a file
//The `|| 1` handles the case when pathname is just "/", making it return "/"
const assumedDirectory = pathname.substring(0, (pathname.lastIndexOf("/") || 1));
console.log(assumedDirectory);
P.S.:
To make your code work both in Deno & Node.js, you could do something like:
function cwd() {
try {
return process.cwd();
}
catch (error) {
if (error instanceof ReferenceError) {
return Deno.cwd();
}
else {
throw error;
}
}
}
// Or otherwise just:
((typeof process === "object") ? process : Deno).cwd();