Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically copy files from package to local directory via postinstall npm script?

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 ../../.

like image 708
Dmitri Zaitsev Avatar asked Jan 14 '16 04:01

Dmitri Zaitsev


4 Answers

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",
  },
like image 75
jordins Avatar answered Jan 02 '23 09:01

jordins


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)
like image 25
David Bradshaw Avatar answered Jan 02 '23 09:01

David Bradshaw


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

like image 33
hexagoncode Avatar answered Jan 02 '23 11:01

hexagoncode


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
like image 37
nothing-special-here Avatar answered Jan 02 '23 10:01

nothing-special-here