Main function in Node.js
June 2020
Unlike most other programming languages or runtime environments, Node.js doesn't
have a built-in special main
function to designate the entry point of a
program. But there is an easy way to achieve this in Node.js, which we will show
in this article.
The pattern is to check if the current module is the main module: require.main === module
. If this is true, the current file has been run directly - as
opposed to have been imported by another file - and in this case we can call the
main
function. Example:
// main.js / main.ts (the filename doesn't matter)
function main() {
console.log("Hello world");
}
if (require.main === module) {
main();
}
References
Like this article? Get notified of new ones: