Deno: __dirname / __filename Polyfill

Created on 16 Apr 2019  路  6Comments  路  Source: denoland/deno

Just an idea to facilitate migrations is to polyfill __dirname and __filename
__dirname can already be polyfilled by using import.meta.url

Edited like @rsp corrected

Most helpful comment

@zekth inspired by this issue I wrote a simple polyfill and put it on GitHub:

You can use it as:

import { __ } from 'https://deno.land/x/dirname/mod.ts';
const { __filename, __dirname } = __(import.meta);

console.log(__dirname);
console.log(__filename);

All 6 comments

Deno.cwd() is like process.cwd() in Node, not like __dirname.
It prints the current working directory, not the directory where the script is in.

You'd have to use import.meta.url and location.href for that

Right my test case was wrong but anyway the addition would be nice.

Using something like this will make the same output as Node:

const __filename = new URL(import.meta.url).pathname;
console.log(__filename);

but with Deno the modules doesn't have to have local filenames so it would work only if:
new URL(import.meta.url).protocol === 'file:'
In other cases you might want to leave the full URL.

@zekth inspired by this issue I wrote a simple polyfill and put it on GitHub:

You can use it as:

import { __ } from 'https://deno.land/x/dirname/mod.ts';
const { __filename, __dirname } = __(import.meta);

console.log(__dirname);
console.log(__filename);

Seems like @rsp has the solution. Closing.

Would be nice for an official solution to be added to std/node/global.ts.

However, the technique of deno-dirname is not able to be directly compatible, as it requires import.meta.url to be passed as an argument to a function call, as such it serves more as ponyfill than a polyfill.

I've created filedirname which offers greater environment compatibility (Deno, Node.js, CJS, and Web Browsers), and can operate as a direct polyfill. It is what make-deno-edition uses for automatic __filename and __dirname compatibility when creating deno editions from Node.js code.

Further inquiry could be done as to wether the filedirname technique could be added directly into std/node/global.ts, as it does not require any arguments to be passed to it, so could be implemented as a getter or a proxy.

Happy to do a PR if direct implementation is called upon, however as the main value of std/node is from tools like make-deno-edition which already includes support for it, then I'm not sure what the value will be.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

justjavac picture justjavac  路  3Comments

ry picture ry  路  3Comments

benjamingr picture benjamingr  路  3Comments

watilde picture watilde  路  3Comments

sh7dm picture sh7dm  路  3Comments