Toby's Log

I found myself needing to get the path to the current script and its directory in a local Node JS script recently. In Common JS scripts, that is available by __filename or __dirname globals, but it isn’t available by the same means in ES modules. Instead, there is import.meta.url, which can be used to get at the directory name if needed, like:

const __filename = import.meta.url.replace(/^file:[\/]+/, '/');
const __dirname = __filename.split('/').slice(0, -1).join('/');