Welcome to the Linux Foundation Forum!

In Detecting Main Module in CJS section I have confusion about module and application

Posts: 3
edited October 2023 in LFW211 Class Forum

Inside 07-Node Module System
there is a section name Detecting Main Module in CJS

Here we have below code

  1. 'use strict'
  2. const format = require('./format.js')
  3.  
  4. if (require.main === module) {
  5. const pino = require('pino')
  6. const logger = pino()
  7. logger.info( format.upper( 'my-package started'))
  8. process.stdin.resume()
  9. } else {
  10. const reverseAndUpper = (str) => {
  11. return format.upper(str).split('').reverse().join('')
  12. }
  13. module.exports = reverseAndUpper
  14. }

Now inside if condition we are checking

  1. require.main === module

and identifying the if section as application.

But as far as I know calling the file by require means module,

  1. node -e "require('./index.js')('hello')"

Now my question is, if calling this file by require means, this file is executed as module.
Then why the if section is comparing require.main === module ?

Seems confusing

Comments

  • Hi,

    Now my question is, if calling this file by require means, this file is executed as module.
    Then why the if section is comparing require.main === module ?

    The require.main === module is necessary just to figure out whether given file is to be executed as module or as application.
    This is the same idiom as Python's

    1. if __name__ == "__main__":
    2. ...

    The example demonstrates that top level statements are executed in either case, regardless if it's executed as an application (i.e. node index.js) or as a module (i.e. require('./index.js')). And if you really need to distinguish these cases, you can use require.main === module.

    Regards,
    Dmytro

  • Posts: 160

    correct as answered by @dmsheiko

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Categories

Upcoming Training