@augment-vir/node
Version:
A collection of augments, helpers types, functions, and classes only for Node.js (backend) JavaScript environments.
50 lines (49 loc) • 1.69 kB
JavaScript
import { basename } from 'node:path';
/**
* Trims arguments list to remove all arguments that take place before the script's file name or
* executable bin name.
*
* @category Node : Terminal
* @category Package : @augment-vir/node
* @example
*
* ```ts
* extractRelevantArgs({
* rawArgs: [
* 'npx',
* 'ts-node',
* './my-script.ts',
* 'arg1',
* '--arg2',
* ], // typically will be process.argv
* binName: 'my-script', // should be your package.json "bin" property name, can be undefined
* fileName: 'my-script.ts', // should be __filename from the script that will be executed
* });
* // will output ['arg1', '--arg2']
* ```
*
* @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
*/
export function extractRelevantArgs({ rawArgs, binName, fileName, errorIfNotFound, }) {
const baseFileName = basename(fileName);
if (!baseFileName) {
throw new Error(`Given file name produced no base file name (with path.basename()): '${fileName}'`);
}
const lastIrrelevantArgIndex = rawArgs.findIndex((arg) => {
const baseArgName = basename(arg);
const matchesFileName = baseArgName === baseFileName;
const matchesBinName = binName ? baseArgName === binName : false;
return matchesFileName || matchesBinName;
});
if (lastIrrelevantArgIndex === -1) {
if (errorIfNotFound) {
throw new Error('Failed to find position of file or bin name in provided args list.');
}
else {
return [...rawArgs];
}
}
else {
return rawArgs.slice(lastIrrelevantArgIndex + 1);
}
}