I'm relatively new to Node.js. I developed a script in Python, and now I want to convert parts of it to Node.js and as a result some gaps have been created that I will need to understand how to execute in Node.js:
for example:
// a.js
function foo(){
console.log("This is function 'foo' which is located in a.js file");
}
// b.js
function bar(){
console.log("This is function 'bar' which is located in b.js file");
}
// main.js
// The desired function:
getFile(foo); // Will return the path of the a.js file
getFile(bar); // Will return the path of the b.js file
So my second question is: is there a way to determine the source of the function in the most deterministic way?
You can only do that from within the function itself (or a function called by that function). But when you do have access to it, then you can use this trick:
console.log((new Error()).stack);
For example:
function foo1() {
console.log((new Error()).stack);
}
foo1();
will print:
> node test.js
Error
at foo1 (/tmp/test.js:2:16)
at Object.<anonymous> (/tmp/test.js:5:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47