0

Let's say I'm running a script at the command line:

coffee ./scripts/doSomeStuff.coffee

where doSomeStuff.coffee looks like:

numberOfTimes = ??? 

doStuff = (times) -> 
  while times > 0 
    console.log('doing stuff') 
    --times 

doStuff(numberOfTimes)

How can I pass in the number of times to do stuff via the command line? --eval seemed like the obvious choice but adding --eval='global.numberOfTimes=5' didn't help.

I can do it with export REPEAT_TIMES=5 from bash but that seems rife with potential side-effects.

1 Answer 1

3

Same way you do with node.js, via process.argv

http://nodejs.org/docs/latest/api/process.html#process_process_argv

Command:

coffee ./scripts/doSomeStuff.coffee 5

CoffeeScript:

numberOfTimes = process.argv[2]
# index 0 is the interpreter: coffee
# index 1 is the file: ./scripts/doSomeStuff.coffee
# index 2 is the first argument: 5

There are also a great number of npm modules that provide nicer interfaces for parsing argv. I've had a good time with optimist myself.

Sign up to request clarification or add additional context in comments.

2 Comments

PLease don't insert code into other peoples answers. I don't want to look like I recommended your way of setting a default, because that's pretty convoluted. That should very simply be: numberOfTimes = process.argv[2] ? 1
You're right I hadn't run that code yet, forgot about the simpler way. I think adding that makes a more complete answer though so I added it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.