pythonnode.jsshlex

Shlex Split Equivalent for Node.js


How would I do the following in Node.js? I realize there's probably no builtin feature or written module for this, so how might I implement this?

>>> import shlex
>>> shlex.split("-a arga -b \"argument b\" arg1 arg2")
['-a', 'arga', '-b', 'argument b', 'arg1', 'arg2']

Solution

  • I assume you've already searched http://npmjs.org (either searching, or browsing the shell keyword) instead of just assuming no such thing exists. At a quick glance, for example, various packages like shell-quote seem likely to do what you want, and others like nshell seem likely to either depend on a shlex-like library or to have equivalent code internally, but I haven't actually looked at any of them in detail, so I'm willing to accept that there's nothing out there you can use.

    Getting all of the details right is complicated. But fortunately, the source code for Python's shlex.split is written in pure Python, and is reasonably readable. So, you should be able to port it.

    If you do this, you should ideally also build a good test suite and publish it as an npm package so that the next time someone else looks, it will exist at http://npmjs.org.