swfz
Posted on October 31, 2022
Not only zx, but when you refer to a command line argument list in node
If you are not using a library to parse command line arguments, the list is taken from process.argv.
I thought I could simply use this for zx as well, but the order in which zx options are passed to process.argv changes, so if I try to use it as-is, the behavior changes, as a matter of course.
minimist
In zx, minimist is included by default, and you can refer to the list of arguments parsed by minimist from the beginning (argv).
If you don't use other libraries, it seems to be a good idea to refer to argv from the beginning.
However, this alone is a little subtle and changes the contents of the command line argument list in the following two patterns
- No options, when you pass a set of key/value options
- eg) --shell=/bin/bash
-
when passing options that can be represented by (true/false)
- eg) --quiet
sample.mjs
#!/usr/bin/env zx
console.log(argv);
$ zx sample.mjs a b c
{ _: [ 'sample.mjs', 'a', 'b', 'c' ] }
$ zx --shell=/bin/bash sample.mjs a b c
{ _: [ 'sample.mjs', 'a', 'b', 'c' ], shell: '/bin/bash' }
$ zx --quiet sample.mjs a b c
{ _: [ 'a', 'b', 'c' ], quiet: 'sample.mjs' }
even if your file name is in the list of command line arguments, exclude it to prevent the command line argument list from being changed by options at runtime.
path
zx also includes path by default, so it is not affected by the runtime options if you exclude your filename from the command line argument list.
- sample.mjs
#!/usr/bin/env zx
console.log(path.basename(__filename));
console.log(argv);
console.log(argv._.filter(a => a !== path.basename(__filename)));
$ zx sample.mjs a b
sample.mjs
{ _: [ 'sample.mjs', 'a', 'b' ] }
[ 'a', 'b' ]
$ zx --quite sample.mjs a b
sample.mjs
{ _: [ 'a', 'b' ], quite: 'sample.mjs' }
[ 'a', 'b' ]
This should no longer affect behavior due to options, etc.
Posted on October 31, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.