Nvm: How can we install and consume NVM using PHP?

Created on 29 Jan 2019  路  6Comments  路  Source: nvm-sh/nvm

Hello,

Actually we're trying to install Node Js using NVM with the PHP language. We're using the given below script to perform the operation. The issue is that the script below is not detecting the "nvm" command for installing node js. We are having to open a new terminal instance to use the "nvm" command. Is there any workaround for this?

<?php

shell_exec('touch ~/.bash_profile');
shell_exec('
            export NVM_DIR=$HOME/nvm &&
            curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash &&
            [ -s "$NVM_DIR/nvm.sh" ] &&
            \. "$NVM_DIR/nvm.sh" &&
            nvm install node &&
            nvm use node
');

Most helpful comment

Note that install auto-uses, so you don鈥檛 need the final use command.

All 6 comments

nvm.sh has to be sourced in each shell that needs it. Generally, you'd source it in the shell that php runs in, so that the $PATH is already set up for when you run shell_exec.

I'm not sure why that second shell_exec command wouldn't be working - what isn't working about it?

It basically says that nvm command is not found even when I've used [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" as it was instructed in the documentation.

That's very strange. What does type nvm and command -v nvm print out after sourcing?

It's fixed thanks. This was my solution to it.

<?php

putenv('NVM_DIR=' . __DIR__ . '/bin');

shell_exec('touch ~/.bash_profile');
shell_exec('curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash && [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" && nvm install node && nvm use node');

Note that install auto-uses, so you don鈥檛 need the final use command.

For the future PHP developers. If anyone would like to use the Node, NPM or NPX within PHP. I have created small library named NodePHP around NVM that will take care of everything.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ksmithut picture ksmithut  路  3Comments

danielepolencic picture danielepolencic  路  4Comments

gsklee picture gsklee  路  4Comments

goalidea picture goalidea  路  3Comments

watson picture watson  路  5Comments