Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to install npm package from nodejs script?

How to install npm package from nodejs script?


How to Install npm package from nodejs script?

Question is not about simple installation npm packages via terminal,
it is about installation via nodejs script:
Not about this: npm install express, but about having install.js file with content npm install express, which I will execute like node install.js and after this it will locally install express module in this folder.

Sorry, but Google and DuckDuckGo are not my friends today(

The main problem is in automatic local installation required packages for my small utility, because global packages are not working in windows.

Problem courtesy of: Vladimir Starkov


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 node

var 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);

  .option('i, --install ', 'install packages')

if (program.install) {
  run('npm install');

var count = 0;

// If parameter is missing or not supported, display help
program.options.filter(function (option) {
  if(!(option.short == process.argv[2]))

if(count == program.options.length);

Hope this helps!

Solution courtesy of: tUrG0n


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to install npm package from nodejs script?


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription