How to install npm package from nodejs script? How to install npm package from nodejs script? node.js node.js

How to install npm package from nodejs script?


Check out commander.js it allows you to write command line apps using node.

Then you can use the exec module.

Assuming you put the following in install.js, you just have to do: ./install.js and it will run npm install for you.

#!/usr/bin/env nodevar program = require('commander');var exec = require('child_process').exec;var run = function(cmd){  var child = exec(cmd, function (error, stdout, stderr) {    if (stderr !== null) {      console.log('' + stderr);    }    if (stdout !== null) {      console.log('' + stdout);    }    if (error !== null) {      console.log('' + error);    }  });};program  .version('0.1.3')  .option('i, --install ', 'install packages')  .parse(process.argv);if (program.install) {  run('npm install');}var count = 0;// If parameter is missing or not supported, display helpprogram.options.filter(function (option) {  if(!(option.short == process.argv[2]))    count++});if(count == program.options.length)  program.help();

Hope this helps!


NOTE: I don't think this fulfills all the requirements of your question, because at the end you state that you can't find npm...so maybe your question would be better titled "How to install npm package without npm?"--yikes! But it addresses the title, "How to install npm package from nodejs script?"

I've just been shown another alternative to do this: the module npmi. While this is still another module dependency, it does at least work without a *nix shell script environment, which I think the other answer here (about commander.js) does. And, if you look inside the code for npmi.js, you'll find it's very short and merely uses the npm module directly in the node script--which you can do yourself if you don't want to add the npmi module.

So in our case we needed a way to install modules without requiring a *nix shell script (to support Windows users), and this fits the bill nicely.

That still doesn't help you if you can't require('npm'). Only thing I can think of there is trying likely absolute paths...you can require('C:\Program Files\Node\packages\x)`, I think--or wherever node's global packages are stored (per user?). Wrap a couple of attempts in try/catch or test for the file's existence first and try to require the npm module whenever you find where the global packages are actually installed? You might tick off a malware scanner :-), but it might work.