I want to automatically copy certain files from an npm
package to user's local directory after running
npm install my-package
I can get them installed by declaring "files"
inside package.json
. The problem is --- the files are not put in the local directory. So I need to run postinstall
script.
But now I don't know where the package is installed (maybe higher up the directory tree), so how can I reliably access the files and copy them to the local directory via the script?
(By local directory I mean --- from where I run npm install my-package
as user consuming the package.)
UPDATE. It seems the postinstall
script runs as npm
owned process with home directory being node_modules/my-package
, so I still don't know how to access user's home directory other than with naive ../../
.
Since npm 3.4 you can use the $INIT_CWD envar: https://blog.npmjs.org/post/164504728630/v540-2017-08-22
When running lifecycle scripts, INIT_CWD will now contain the original working directory that npm was executed from.
To fix you issue add to your postinstall script in package.json the following:
"scripts": {
"postinstall": "cp fileYouWantToCopy $INIT_CWD",
},
After a lot of searching I found this works cross platform
"scripts":
"postinstall": "node ./post-install.js",
// post-install.js
/**
* Script to run after npm install
*
* Copy selected files to user's directory
*/
'use strict'
var gentlyCopy = require('gently-copy')
var filesToCopy = ['.my-env-file', 'demo']
// User's local directory
var userPath = process.env.INIT_CWD
// Moving files to user's local directory
gentlyCopy(filesToCopy, userPath)
var cwd = require('path').resolve();
Note: If the arguments to resolve have zero-length strings then the current working directory will be used instead of them.
from https://nodejs.org/api/path.html
I would use shellscript/bash
-package.json
"scripts":
"postinstall": "./postinstall.sh",
-postinstall.sh
#!/bin/bash
# go to YOUR_NEEDED_DIRECTORY .e.g "dist" or $INIT_CWD/dist
cd YOUR_NEEDED_DIRECTORY
# copy each file/dir to user dir(~/)
for node in `ls`
do
cp -R $node ~/$node
done
Don't forget to!
chmod +x postinstall.sh
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