When a file is run directly from Node.js, require.main is
set to its module.
app.js
if (require.main === module) { console.log('Application called directly'); } else { console.log('app.js module is loaded using require module'); }
test.js
const app = require('./app');
When you ran app.js directly using node command line
tool, you can see below message.
$ node app.js
Application called directly
When you ran test.js, you can see below message in
console.
$ node test.js
app.js module is loaded using require module
If you are building web applications using express
module, you may require to know, whether application is launched directly by
node command line tool (or) by require module.
index.js
//Load express module const express = require('express'); //Put new Express application inside app variable const app = express(); const PORT = 9090; //When user hits the home page, then the message prints in browser. app.get('/', (req, res) => res.send('Welcome to Node.js Programming')); if (module === require.main) { const PORT = process.env.PORT || 9090; app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); }); } module.exports = app;
Reference
No comments:
Post a Comment