~/src/node-playground(master#%)[0]
$ cat example-main_and_exports.js
#!/usr/bin/env node
const lib = require('./lib.js')
const doA = () => { lib.A() }
const doB = () => { lib.B() }
const doC = () => { lib.C() }
const main = () => {
doA()
doB()
doC()
}
if (require.main === module) {
main()
} else {
exports.doA = doA
exports.doB = doB
exports.doC = doC
}
bronoric@bruno-mbp:~/src/node-playground(master#%)
$ cat lib.js
#!/usr/bin/false
exports.A = () => { console.log(`Did A.`) }
exports.B = () => { console.log(`Did B.`) }
exports.C = () => { console.log(`Did C.`) }
~/src/node-playground(master#%)[0]
$ ./example-main_and_exports.js
Did A.
Did B.
Did C.
~/src/node-playground(master#%)[0]
$ ./lib.js
~/src/node-playground(master#%)[1]
$ node -e "require('./example-main_and_exports.js').doA()"
Did A.
~/src/node-playground(master#%)[0]
$ node -e "require('./example-main_and_exports.js').doB()"
Did B.
~/src/node-playground(master#%)[0]
$ node -e "require('./example-main_and_exports.js').doC()"
Did C.
Created
February 11, 2020 17:42
-
-
Save RichardBronosky/9377f5283fcddd4a3bc536a6c9f5ff7b to your computer and use it in GitHub Desktop.
Pattern for using `main` and `exports` in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const lib = require('./lib.js') | |
const doA = () => { lib.A() } | |
const doB = () => { lib.B() } | |
const doC = () => { lib.C() } | |
const main = () => { | |
doA() | |
doB() | |
doC() | |
} | |
if (require.main === module) { | |
main() | |
} else { | |
exports.doA = doA | |
exports.doB = doB | |
exports.doC = doC | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/false | |
exports.A = () => { console.log(`Did A.`) } | |
exports.B = () => { console.log(`Did B.`) } | |
exports.C = () => { console.log(`Did C.`) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment