What does 'if (!module.parent)' mean in NodeJS?
In NodeJS applications you often see code like
if (!module.parent) {
app.listen(3000);
}
This means: Run app.listen(3000)
only if you are running the file
Suppose this code is in index.js
. In this case, the code will only be executed if you run index.js
directly (i.e. using node index.js
) and not if index.js
is require
d from another file (by require('./index.js');
).
If index.js
is required from another Javascript module (i.e. file), module.parent
will be set to that module.