Skip to content

Instantly share code, notes, and snippets.

@khrome
Last active September 16, 2023 17:33
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save khrome/7d87534748545f576fd2 to your computer and use it in GitHub Desktop.
Save khrome/7d87534748545f576fd2 to your computer and use it in GitHub Desktop.
__dirname in the browser
(function(){ //make __dirname, __filename work in the browser
if(window && !window['__dirname']){
var stackTrace = function () {
var lines = (new Error()).stack.split("\n");
// 0 = message, 1 = stackTrace
lines.shift(); lines.shift();
var result = lines.map(function(line){
if(line.indexOf('(native)') != -1){
return {
file : '[browser core]',
directory : '-',
domain : line.replace(' at ', '').replace('(native)').trim()
}
}
var parts = (RegExp(' (?:at(?: .*?)? |\\\()(.*):([0-9]+):([0-9]+)', 'g').exec(line));
//console.log(parts, line);
var sep = parts[1].lastIndexOf('/');
var directory = parts[1].substring(0, sep);
var urlTest = (/([a-zA-Z]+:\/\/.*?)\/(.*)/g).exec(directory);
var domain;
//console.log('parts', parts)
if(urlTest){
domain = urlTest[1];
directory = urlTest[2];
}
return {
file : parts[1].substring(sep+1),
directory : directory,
line : parts[1],
column : parts[2],
domain : domain
}
})
return result;
}
Object.defineProperty(window, "__filename", {
__proto__: null, // no inherited properties
get : function(){
var stack = stackTrace();
stack.shift();
return stack[0].file;
}
});
Object.defineProperty(window, "__dirname", {
__proto__: null, // no inherited properties
get : function(){
var stack = stackTrace();
stack.shift();
return stack[0].directory;
}
});
Object.defineProperty(window, "__stacktrace", {
__proto__: null, // no inherited properties
get : function(){
var stack = stackTrace();
stack.shift();
return stack;
}
});
}
})();
@Fasteroid
Copy link

very cursed, I like it

@khrome
Copy link
Author

khrome commented Sep 16, 2023

Thanks!

I'm shifting to es modules which has it's own solution for this, so this is more of a legacy shim these days.

In the new world I had to build solutions for everything else, though ( package.json/ canvas/ webcomponents etc. ).

There is no silver bullet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment