2

In NodeJS, Given a function handle, how to find the file or module where such function was declared?

For example:

// File 1

import { test } from './file1'

function fileFile(fn: Function){
   //... here's my issue
}

console.log(findFile(test)) // Logs '~/a/b/file1.js'

// File 2

export const test = ()=> true

I have tried different approaches, from using v8 to require. I cannot find a proper way to do this. I thought of finding the fn.toString() contents but wont be so reliable.

Thoughts?

5
  • 2
    There is no direct way to do it is what I think. The reason being: functions can be passed around, re-assigned, and imported/exported across modules. There can be hacky inefficient way although. Having said that, If you have control over the codebase, one alternative is to add metadata to your functions, which includes information about their source files. You can then use this metadata to find the file where the function was declared. Commented Dec 28, 2023 at 17:19
  • 1
    I'm thinking about using decorators for this. It might be the only option. But before working on that I wanted to exhaust all possible options. Thanks for the reply @mandy8055 Commented Dec 28, 2023 at 17:34
  • 1
    ECMAScript doesn't standardize this. But I'm confident v8 stores it somewhere. It's used when a script causes an error and reports a stacktrace with the filenames. Be aware that some functions don't have origins with nice filenames / urls, such as those that were built from an eval instruction. I do not think this is accessible via script via v8 or vm modules, as you tried, but you may be able to write a native addon (likely ABI unstable) that pulls the info from the function. The chain is likely: function -> script -> source url but I can't point to the exact code yet. Still looking Commented Dec 28, 2023 at 18:02
  • For some reason I didn't see the [[FunctionLocation]] member within the Function. Will report back to see if it's works. (node 18) Commented Dec 28, 2023 at 20:45
  • 1
    Update: Found this stackoverflow.com/a/55564765/6022629 by searching '[[FunctionLocation]]'. Checking it out. Commented Dec 28, 2023 at 20:53

1 Answer 1

1

Even after searching and asking several AI bots. I did not find it. But there was a solution.

I found by mere chance [[FunctionLocation]], and then when I searched for that specific words, then I found https://github.com/midrissi/func-loc

With that I was good to go.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.