Search code examples
yargsnode-commanderminimist

passing string with spaces to node cli-parser


var minimist = require("minimist")

const a = minimist(`executable --param "a b"`.split(' '))
console.log(a)

https://runkit.com/embed/57837xcuv5v0

actual output:

Object {_: ["executable", "b\""], param: "\"a"}

expected output:

Object {_: ["executable"], param: "a b"}


I'm also seeing same result when using yargs and commander.

It's strange because jest is using yargs and jest accept the following command: jest -t "test name with spaces"


Solution

  • Based on your example code, the problem is your preparation of the string array which has broken up the string-with-spaces before the parser gets to see it:

    $ node -e 'console.log(`executable --param "a b"`.split(" "))'
    [ 'executable', '--param', '"a', 'b"' ]
    

    A simple fix when manually setting up the arguments is to construct the array of parameters yourself, instead of using a string and split, like:

    $ node -e 'console.log(["executable", "--param", "a b"])'   
    [ 'executable', '--param', 'a b' ]
    

    or

    const a = minimist(['executable', '--param', 'a b'])
    

    If what you need to do is break up a single string into arguments like the shell does, that is not done by Commander, or minimist.

    You could look at https://www.npmjs.com/package/shell-quote which has a parse command.


    Yargs does have a mode where it does the splitting, if you pass in a single string rather than an array of strings.

    const yargs = require('yargs/yargs');
    const argv = yargs('executable --param "a b"').parse();
    console.log(argv);
    
    % node index.js 
    { _: [ 'executable' ], param: 'a b', '$0': 'index.js' }