💦 Split a command into an array or an object
Useful for splitting a command to use with NodeJS' child process methods, like spawn, exec, and execFile, as well with libs like execa.
âš¡ Just 0.4 KB uncompressed, no external dependencies.
🎯 Version 1.1
+ works with NodeJS, DenoJS and browsers. JavaScript and TypeScript.
npm i split-cmd
import { split } from 'split-cmd';
const arr = split( 'git commit -m "some message with spaces"' );
console.log( arr ); // [ "git", "commit", "-m", "some message with spaces" ]
import { splitToObject } from 'split-cmd';
const obj = splitToObject( 'git commit -m "some message with spaces"' );
console.log( obj.command ); // git
console.log( obj.args ); // [ "commit", "-m", "some message with spaces" ]
import { splitToObject } from 'split-cmd';
import { execa } from 'execa';
// Executing a single command
const obj = splitToObject( 'echo "I see unicorns"' );
execa( obj.command, obj.args )
.then( result => console.log( result.stdout ) ) // I see unicorns
.catch( error => console.log( error ) );
// Executing multiple commands in batch
[
'echo "I see unicorns"',
'mkdir foo',
'touch foo/bar.txt'
]
.map( s => splitToObject( s ) )
.forEach( obj => {
execa( obj.command, obj.args )
.then( result => console.log( result.stdout ) )
.catch( error => console.log( error ) );
} );
/**
* Split a command into an array.
*
* @param {string} command Command to split.
* @returns {Array}
*/
split( command: string ): string[]
/**
* Split a command into an object with the attributes `command` and `args`.
*
*
* @param {string} command Command to split.
* @returns {object}
*/
splitToObject( command: string ): { command?: string, args?: string[] }
MIT © Thiago Delgado Pinto