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 ?
You can easily run scripts using npm by adding them to the "scripts" field in package. json and run them with npm run <script-name> . Run npm run to see available scripts. Binaries of locally install packages are made available in the PATH , so you can run them by name instead of pointing to node_modules/.
Life Cycle Operation Order js file in the root of your package, then npm will default the start command to node server. js . prestart and poststart will still run in this case.
The npm install installs all modules that are listed on package. json file and their dependencies. npm update updates all packages in the node_modules directory and their dependencies.
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.
For anyone else stumbling here npm doesn't run pre/postinstall in the package.json when installing a specific package. You can check here for reference, https://npm.community/t/preinstall-npm-hook-doesnt-execute-when-installing-a-specific-package/2505. Not sure if there is a way around it but I've been looking too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With