Aleksandrenko
Aleksandrenko

Reputation: 3065

improving express.js module usage

There is something small but it annoys me. When you want to use a node module you have to manually install it, required it and add it in package.json. If you don't want to use it it's the same thing backwards.

Is there a tool that install/remove to/from node_modules & add/remove to/from package.json automatically after module is required.

It's something simple that must exists if not now later on.

Upvotes: 1

Views: 274

Answers (3)

zemirco
zemirco

Reputation: 16395

That's quite an interesting question. I couldn't find a solution so I wrote a small script myself. Imagine you have your main file with the following content.

index.js:

var colors = require('colors');
console.log('this comes from my main file');

In case you don't have colors installed and run node index.js you'll get the error Error: Cannot find module 'colors'.

To make this work create another module.js file that you will run instead of your index.js file.

module.js:

var exec = require('child_process').exec;

try {
  // require your main file here
  require('./index');
} catch(e) {
  if (e.code === 'MODULE_NOT_FOUND') {
    var message = e.message;
    console.log(message);
    var module = message.match(/\'([a-z]+)\'/)[1];
    console.log('Installing ' + module + ' ...');
    exec('npm install ' + module + ' --save', function(error, stdout, stderr) {
      if (error) console.log(error);
      console.log(JSON.stringify(stdout).replace(/\\n/g, "") + ' successfully installed');
    });
  }
}

Now run node module.js and you'll get the following

Cannot find module 'colors'
Installing colors ...
"[email protected] node_modules/colors" successfully installed

If you run node module.js again you'll get

this comes from my main file // this is what you want

and colors is added to your package.json file. You can reuse module.js in every project and just have to change the require function to get the right file.

Upvotes: 3

staackuser2
staackuser2

Reputation: 12412

I am not aware of any tool that will automatically install a package when you modify source code. Shouldn't be that hard to make if you really want it though :)

As Kyle said, --save can work for what you want. There is also npm shrinkwrap that will take a snapshot of your node_modules and update the file it manages for you. Just check that file into git, and then if you deploy to Heroku (or anywhere else that uses npm install), it will use that instead of the package.json file for dependencies.

Upvotes: 1

Kyle Robinson Young
Kyle Robinson Young

Reputation: 13762

npm can do it with the --save flag: npm install [package] --save or npm install [package] --save-dev for devDependencies. Check out the npm install docs: https://npmjs.org/doc/install.html

Upvotes: 1

Related Questions