Welcome to the Linux Foundation Forum!

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

raselkarim7
raselkarim7 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

'use strict'
const format = require('./format.js')

if (require.main === module) {
    const pino = require('pino')
    const logger = pino()
    logger.info( format.upper( 'my-package started'))
    process.stdin.resume()
} else {
    const reverseAndUpper = (str) => {
        return format.upper(str).split('').reverse().join('')
    }
    module.exports = reverseAndUpper
}

Now inside if condition we are checking

require.main === module

and identifying the if section as application.

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

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

    if __name__ == "__main__":
        ...
    

    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

  • xdxmxc
    xdxmxc Posts: 157

    correct as answered by @dmsheiko

Categories

Upcoming Training