Search code examples
node.jsgitubuntunpmdigital-ocean

How run npm on deploy project via git? (hooks/post-receive: npm: command not found)


Problem

I created a project where configure a server in DigitalOcean with Apache and Git.

For init project on server, I run the following command:

cd /var/repo
mkdir project-example.git && cd project-example.git
git init --bare

I set up file post-receive with this code:

#!/bin/bash
git --work-tree=/var/temp/project-example --git-dir=/var/repo/project-example.git checkout -f
cd /var/temp/project-example
npm install
npm run build
rm -rf /var/www/project-example/*
mv -f /var/temp/project-example/build/* /var/www/project-example/

When I make a push to server remote via git on machine local, occurs followings errors:

remote: hooks/post-receive: line 4: npm: command not found
remote: hooks/post-receive: line 5: npm: command not found

However, accessing server via SSH and execute command:

# it works standard
cd /var/repo/project-example.git
source hooks/post-receive

Comments

System Server: Ubuntu 14.04

I installed node via nvm.


Solution

  • When a git hook runs, it does not necessarily have the same PATH variable set as when you log in via SSH. Try putting the full path to npm in your script when you call it; that should fix things.

    UPDATE (June 7 2019):

    A couple of commenters had issues with node not being found when using the above solution, which made me realize it is not very robust. Rather than put the path in the call to npm itself, you'd be better off adding the necessary path to the script's environment, e.g. if npm (and node) happen to be in /usr/bin/, add the following to your script before calling npm:

    export PATH=$PATH:/usr/bin
    

    In fact, a more robust way to make sure the hook works the same as it does when you are logged in via SSH is to find out what the path is when you are logged in (i.e. the output of echo $PATH) and set the path in your hook script accordingly (of course you may need to omit some user-specific paths, etc.)