Pattern for if(require.main) that works on Azure's iisnode

134 views Asked by At

A pattern seen in both Node and Python development that allows a module to be used both standalone and as a module looks like this:

function main() {
    // ....
}

if(require.main === module) {
    main();
}

module.exports = {
    start : main
}

Unfortunately, this does not work on Microsoft's Azure cloud service, as iisnode overwrites require.main with something else (not sure what). How can I rewrite the check to work on Azure as well, starting the main module if it is the main entry point?

1

There are 1 answers

0
oligofren On

I only found a hackish solution to this problem, which basically detects whether I am running iisnode or not:

var onIISNode = require.main.filename.match(/iisnode/);
if(onIISNode || require.main === module){ ... }

Improvements are welcome ... especially ones actually using the official Azure API for NodeJS