Wednesday 20 March 2019

Node.js: How can you detect whether a file is directly run from node or not?


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



Previous                                                 Next                                                 Home

No comments:

Post a Comment