package.json: how to test if node_modules exists

Viewed 4091

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.

4 Answers

I thought I would post what I've done for cross-platform one-liner conditional NPM scripts.

"scripts": {
    "start":"(node -e \"if (! require('fs').existsSync('./node_modules'))
{process.exit(1)} \" || echo 
'node_module dir missing: use npm run dist') && node start-app.js",
}

Yes it is, via npm scripts. Which npm script to use is your choice. If your application starts via npm start (good practice) use the start script to add your check:

"scripts": { "start" : "./test.sh" }

The actual test for the directory can be implemented via a shell script or a NodeJs script, consider using npx as discussed in Difference between npx and npm?.

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!

With this script I have run yarn install in subfolder app of my project dir (if node_modules not exist)

const fs = require('fs');
const path = require('path');
const spawn = require('cross-spawn');

if (!fs.existsSync(path.resolve(__dirname, '../app/node_modules'))) {
  
  const result = spawn.sync(
    'yarn',
    ['--cwd', path.resolve(__dirname, '../app'), 'install'],
    {
      stdio: 'inherit'
    }
  );
  console.log(result);
}
Related