node.jsnpmnpm-scriptsnpm-run

package.json: how to test if node_modules exists


Inside package.json, is it possible to test if node_modules directory exists? My goal is to print a message if node_module does not exists, something like:

node_module not existent: use npm run dist

where dist is a script inside scripts of my package.json. Thank you.


Solution

  • As suggested by B M in comments, I've created the following script named checkForNodeModules.js:

    const fs = require('fs');
    if (!fs.existsSync('./node_modules'))
      throw new Error(
        'Error: node_modules directory missing'
      );
    

    And inside my package.json:

    "scripts": {
      "node-modules-check": "checkForNodeModules.js",
      "start": "npm run node-modules-check && node start-app.js",
    }
    

    Thanks!