argv-split
Split argv(argument vector) and handle special cases, such as quoted or escaped values.
Why?
const split = require('split')
const mkdir = 'mkdir "foo bar"'
mkdir.split(' ')
split(mkdir)
const mkdir2 = 'mkdir foo\\ bar'.split(' ')
mkdir2.split(' ')
split(mkdir2)
argv-split
handles all special cases with complete unit tests.
foo a\ b
foo \'
foo \"
foo "a b"
foo "a\ b"
foo '\'
foo --abc="a b"
foo --abc=a\ b
foo \
--abc=a\ b
split('foo \\\n --abc=a\\ b')
Error Codes
UNMATCHED_SINGLE
If a command missed the closing single quote, the error will throw:
Shell command:
foo --abc 'abc
try {
split('foo --abc \'abc')
} catch (e) {
console.log(e.code)
}
UNMATCHED_DOUBLE
If a command missed the closing double quote, the error will throw:
foo --abc "abc
ESCAPED_EOF
If a command unexpectedly ends with a \
, the error will throw:
foo --abc a\
foo --abc a\
NON_STRING
If the argument passed to split
is not a string, the error will throw
split(undefined)
Install
$ npm i argv-split
Methods
split(string) -> Array
Splits a string, and balance quoted parts. The usage is quite simple, see examples above.
Returns Array<string>
split.join(args, options?) -> string
Join the given array of argument vectors into a valid argument string
New in 3.1.0
- args
Array<string>
arguments to be joined - options?
Object=
- quote
string="
should we use single quote or double quote when a certain argument needs to be quoted. Defaults to "
'command ' + join(['foo "bar', "'baz"])
Handle Line Feeds
There is a special value of split.LF
which could help us to create valid commands with line feeds:
'kubectl' + join(['apply', '--prune', '-f', 'manifest.yaml', split.LF, '-l', 'app=nginx'])
License
MIT