0

In ES6 and later we prefer import over require.

In the absence of the require object, how does one access values historically presented as attributes of the require object? For example, require.main.filename

If there is a topic in the Node documentation dealing with this a reference would be greatly appreciated. In the meantime, I persist while Google fails to be my friend... obviously I'm asking the wrong question. Better search terms would also be helpful.

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
Peter Wone
  • 16,657
  • 12
  • 76
  • 114
  • https://nodejs.org/api/esm.html#importmeta is all there currently is – Bergi Dec 05 '21 at 00:35
  • See also [Detect whether ES Module is run from command line in Node](https://stackoverflow.com/q/57838022/1048572) for `.main` specifically – Bergi Dec 05 '21 at 00:38
  • 1
    You read the Node.js documentation on ES modules and then you search Stackoverflow on a per-use-case basis for anything you couldn't find in the docs (after filing a docs update request on node.js's documentation issue tracker)? At this point there is nothing you can possibly need that someone else hasn't asked about already. – Mike 'Pomax' Kamermans Dec 05 '21 at 00:39
  • 1
    @Mike'Pomax'Kamermans "*What happened to the properties of `require` in ES modules?*" is a perfectly valid question. Sure, there are [duplicates](https://stackoverflow.com/q/64180480/1048572) for the particular use case, but nobody has asked the general question so far. – Bergi Dec 05 '21 at 00:45
  • @Bergi Presumably because the general question is covered by https://nodejs.org/api/esm.html (it was a big change, a lot of work went into making sure the docs actually covered what people needed to know), which has sections covering "what do I use instead of ..." and anything not covered would certainly already be covered by other SO questions on a per-use-case basis. – Mike 'Pomax' Kamermans Dec 05 '21 at 00:46
  • @Bergi thanks for the timely, correct and actionable comment. Turn it into an answer so I can accept it before rule obsessed meddlers close this question. – Peter Wone Dec 05 '21 at 05:41
  • @Mike'Pomax'Kamermans that argument is also an argument for closing down Stack Overflow. – Peter Wone Dec 05 '21 at 05:46

1 Answers1

0

Accessing properties on the require function has been replaced by accessing the import.meta object in ES modules. It allows implementations to expose metadata about the module in a standard location.

Node.js in particular currently supports import.meta.url (like CommonJS __filename and __dirname) and import.meta.resolve (like require.resolve). The discussion about adding import.meta.main appears to have stalled.

Bergi
  • 572,313
  • 128
  • 898
  • 1,281