filedirname
Version:
Fetch the current file and directory path, no matter your environment (Deno, Node.js, Web Browsers, ESM, CJS)
57 lines (56 loc) • 1.85 kB
JavaScript
// external
import getCurrentLine, { getFileFromError } from 'get-current-line';
import fileURLToPathShim from '@bevry/file-url-to-path';
// builtin
import { fileURLToPath as fileURLToPathNode } from 'url';
import { dirname, sep } from 'path';
/**
* Ensure we have a filepath rather than a URL.
* Assumes the path is correct, in that it uses the correct seperator and is already resolved, as we do not do any modifications if not a file: URL.
*/
function filepath(path) {
// if already a path, or if a URI that cannot be converted, return as is
if (!path.startsWith('file:'))
return path;
// otherwise convert file: to path
if (typeof fileURLToPathNode !== 'undefined') {
// Node.js v10+
return fileURLToPathNode(path);
}
else {
// Node.js <v10
return fileURLToPathShim(path, sep);
}
}
/** Fetch the file and directory paths from a path, uri, or `import.meta.url` */
export function filedirnameFromPath(path) {
const file = filepath(path);
const directory = dirname(file);
return [file, directory];
}
/** Fetch the file and directory paths from an Error instance. */
export function filedirnameFromError(error) {
return filedirnameFromPath(getFileFromError(error));
}
/** Fetch the file and directory paths from the caller. */
export function filedirnameFromCaller() {
return filedirnameFromPath(getCurrentLine({
method: 'filedirname',
frames: 0,
immediate: false,
}).file);
}
/** Fetch the file and directory paths from one of the overloads. */
function filedirname(arg) {
// nothing
if (arg == null) {
return filedirnameFromCaller();
}
// string
if (typeof arg === 'string') {
return filedirnameFromPath(arg);
}
// error
return filedirnameFromError(arg);
}
export default filedirname;