Coding ยท ยท

Command line arguments

Earlier you learnt about taking input from a user with prompt() or confirm() or by reading a file, and outputting with console.log() or writing to a file. Another way of taking input is by arguments on the command line.

Create a file arguments.js and add this to it:

console.log(Bun.argv)

When we run the file with bun arguments.js we see something like:

[ "/home/jake/.bun/bin/bun", "/home/jake/code/arguments.js" ]

Without changing the file, run it instead with bun arguments.js something whatever, and we get output like this:

[ "/home/jake/.bun/bin/bun", "/home/jake/code/arguments.js", "something", "whatever" ]

To access that word something we can do Bun.argv[2] as it's in the 3rd index of the array. Equally, we could get the word whatever with Bun.argv[3].

Let's change arguments.js to the following:

let max = Bun.argv[2]
for (let i = max; i > 0; i--) console.log(i)

...and run it with bun arguments.js 3. It kind of works but the first line of output is white rather than yellow because it treats all command line arguments as strings rather than numbers. We should do similar checks as normal to coerce the input to the correct type and ensure it's in the right range.

let max = Number(Bun.argv[2])
if (Number.isInteger(max) && max > 0) {
  for (let i = max; i > 0; i--) console.log(i)
} else {
  console.error('Enter a positive integer')
}

Notice also the use of console.error() above, which is just like console.log() but in red.

There is more you can do with command line arguments in Bun. Many programs take command line arguments and flags. You learnt about some earlier, and now you know how your program can use them too.