Search code examples
node.jsnpmnpm-installnode-modulesnpm-scripts

How to run a post-install script after individual execution of "npm install <package>"


I am maintaining the following directory structure:

/home/user/Desktop/
                 |-- app/
                 |      |-- package.json
                 |      `-- server.js
                 |-- node/
                 |      |-- bin/
                 |      |      |-- node
                 |      |      `-- npm
                 |      |-- include/
                 |      |-- lib/
                 |      `-- share/
                 |
                 `-- npm.sh

I want all my locally installed node modules reside in the directory node. That is, if I run npm install inside the directory app, initially it'll install the modules inside the current directory (app) and then move the node_modules folder to the external directory called node. For this purpose I've written a script npm.sh and placed the mv (move) command inside the postinstall script of package.json.

These are the files npm.sh and package.json.

content of npm.sh:

#/bin/bash

export PATH=/home/user/Desktop/node/bin:$PATH
export NODE_PATH=/home/user/Desktop/node/node_modules
export NODE_MODULE_ROOT=/home/user/Desktop/node
/bin/bash

content of app/package.json:

{
  "name": "app",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "mv node_modules $NODE_MODULE_ROOT",
    "start": "node server.js"
  },
  "dependencies": {
    "jwt-simple": "^0.5.1"
  }
}

But the problem is: when I do ./npm.sh && cd app && npm install, everything works as intended. But when I do npm install jwt-simple, the postinstall script is not getting executed.

Is there a way to make it work for individual npm install <package> ? Or is there any better way to accomplish this ?


Solution

  • You can use npm hook scripts to do something after package is installed.

    Create node_modules/.hooks/postinstall executable and it will be run also after npm install <package>.

    NOTE: I have noticed problems with npm hook scripts between npm version 5.1.0 until 6.0.1. So if you have problems with hooks, check your npm version and upgrade if necessary.