0

Starting to use Node.js more I was wondering if Node.js could actually be tested with a do shell but I've run into an issue. I did a search to see if this was asked but closest result was "Automator - Running Node Command in AppleScript Error".

Here are my attempts:

tell application "System Events" to set username to name of current user
set nodePath to "/Users/" & username & "/.nvm/"
set nodeCommand to "cd " & quoted form of nodePath & " node --version"
try
    set result to do shell script nodeCommand
    return result
on error result
    return "ERROR:" & result
end try

my result is "". Modified change to:

tell application "System Events" to set username to name of current user
set nodePath to "/Users/" & username & "/.nvm/"
set nodeCommand to quoted form of nodePath & " npm config list"
try
    set result to do shell script nodeCommand
    return result
on error result
    return "ERROR:" & result
end try

my result is "ERROR:sh: /Users/username/.nvm/: is a directory". Is there a way to check Node.js version similar to the Terminals command npm config list or node -v?

1

I have node installed in the directory /usr/local/bin, so this command will return the version:

do shell script "/usr/local/bin/node -v"

A couple other scripting points:

  • You needn't use System Events to obtain the user's username. If all you need is the username, you can use

    short user name of (system info)
    
  • However, it looks like you were trying to get the path to your user home folder. In AppleScript, this can be done like so:

    POSIX path of (path to home folder)
    
  • However, as that was all going to be plugged in to a do shell script command, none of that is necessary, as you can use ~ to denote your home folder, and the shell will automatically expand this for you (provided it's not inside any quotes):

    do shell script "cd ~/.nvm/"
    
  • There's no need to set result to. result will automatically contain the result of the previous AppleScript command. return result will work fine without needing to set result to.

0

As a general rule, if you're having trouble with a set of code, try to create the simplest possible test case so you can be sure where the bug is.

I created a one line applescript:

set nodeVersion to do shell script "node --version"

This does indeed fail to work. Applescript says: error "sh: node: command not found" number 127

So the problem is that for some reason, sh can't find the node binary when run via Applescript. So I decided to try specifying the full path:

set nodeVersion to do shell script "/usr/local/bin/node --version"

It worked! Not sure why this is necessary, but it should fix the problem.

(Your path will likely be the same as mine, but if the above still doesn't work, try running which node in a terminal window to find what path you need.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .