nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.47k stars 282 forks source link

ESM loader v20.3.0 access parent path #4190

Closed kirrg001 closed 4 months ago

kirrg001 commented 1 year ago

Details

Hi there!

In Node v18 the loader was able to easily access all cmd line args viaprocess.argv.

node --experimental-loader ./loader.mjs /opt/app/server.mjs

loader.mjs

console.log(process.argv)

[ '.../node/v18.16.0/bin/node', '/opt/app/server.mjs' ]

But with the off-thread change, the process.argv are no longer complete.

[ '.../node/v20.3.0/bin/node' ]

The second entry is missing. The path to the app is missing.

I found a workaround, but I am not really happy with it. Wondering if there is an easier way. When using the resolver hook, it is possible to get the parent path.

loader.mjs

let appSpecifier;
export async function resolve(specifier, context, nextResolve) {
  if (!appSpecifier) {
    appSpecifier = specifier;
    process.argv[1] = appSpecifier.replace('file://', '');
    ...
  }

  return nextResolve(specifier, context, nextResolve);
}

This is important for APM tools, because we auto-load a tracer tool inside the loader to monitor an app. And we need access to the app path.

Node.js version

v20.3.0

Example code

See above.

Operating system

darwin

Scope

See above.

Module and version

Not applicable.

JakobJingleheimer commented 1 year ago

Are you perhaps looking for context.parentURL? That is the url of the entry-point: ex node ./main.mjs parentURL would be cwd + main.mjs

kirrg001 commented 1 year ago

Are you perhaps looking for context.parentURL?

This would work too, but it is undefined for the first entry.

console.log(specifier, context) module/src/app.js, { conditions: [ 'node', 'import', 'node-addons' ], importAssertions: undefined, parentURL: undefined }

In general I am looking for a solution without using the hooks. If you have any idea, let me know :)

giltayar commented 1 year ago

Pass it to the loader via the globalPreload port mechanism (https://nodejs.org/api/esm.html#globalpreload). It's clunky, but it should work.

github-actions[bot] commented 5 months ago

It seems there has been no activity on this issue for a while, and it is being closed in 30 days. If you believe this issue should remain open, please leave a comment. If you need further assistance or have questions, you can also search for similar issues on Stack Overflow. Make sure to look at the README file for the most updated links.

github-actions[bot] commented 4 months ago

It seems there has been no activity on this issue for a while, and it is being closed. If you believe this issue should remain open, please leave a comment. If you need further assistance or have questions, you can also search for similar issues on Stack Overflow. Make sure to look at the README file for the most updated links.