Is it possible to get the file name of the current JavaScript module?
// item.mjs
function printName() {
console.log(...); // >> item or item.mjs
};
If not, why not? Sandboxing, etc.
Is it possible to get the file name of the current JavaScript module?
// item.mjs
function printName() {
console.log(...); // >> item or item.mjs
};
If not, why not? Sandboxing, etc.
You are looking for the (proposed) import.meta
meta property. What exactly this object holds depends on the environment, but in a browser you can use
// item.mjs
function printName() {
console.log(import.meta.url); // https://domain.example/js/item.mjs
}
You can extract the file name by parsing that with the URL
interface, e.g.
console.log(new URL(import.meta.url).pathname.split("/").pop())
import { basename, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const filename = basename(__filename);
Alternatively, use zx
script runner that sets __filename
, __dirname
.
One potential solution: Each method in the mjs file may set a global variable that will be the name of the module. The printName()
method would then print the current value of that global variable. That way, while processing, you can inspect the current state of that global variable for the name of the file currently executing.
global js
var global_mjs_name = 'none';
function printName() {
console.log('processed in ' + global_mjs_name);
}
window.addEventListener('DOMContentLoaded', function(event){
printName(); // output -> 'none'
doWork({});
printName(); // output -> 'item.mjs'
doFunStuff();
printName(); // output -> 'FunStuff.mjs'
});
inside item.mjs:
const item_js_name = 'item.mjs';
function doWork(data) {
global_mjs_name = item_js_name; // every time you execute code within the module, update the global variable
return processData(data);
}
inside some other module called FunStuff.mjs
const funstuff_js_name = 'FunStuff.mjs';
function doFunStuff() {
global_js_name = funstuff_js_name; // update the global variable for the module
return haveFun();
}
I'm not saying this is the best way to accomplish this task. Manually handling the changing of the global variable may be a pain.