Reputation: 27
I am sending the following text through the command line and not sure how to extract the different names in the -q tag
command: -s 127.0.0.1:3000 -q test1.pdf test2.pdf test3.pdf test4.pdf-v 7
The number of file names being sent in can change
This is how I am currently parsing through
var s = process.argv.indexOf('-s') + 1;let files = process.argv.indexOf('-q') + 1; let version = process.argv.indexOf('-v') + 1;
let fileName = process.argv[files ].split(' ')
Any recommendations on what to try?
Upvotes: 1
Views: 145
Reputation: 1435
Normally for command line arguments, if each test*.pdf file was supposed to belong to the -q option, I would expect to see them listed as either:
-q "test1.pdf,test2.pdf,test3.pdf,test4.pdf"
or
-q test1.pdf -q test2.pdf -q test3.pdf -q test4.pdf
Both of these styles will make the logic much easier to parse in addition to being a more conventional style.
Also, I would suggest you look into the yargs module (https://yargs.js.org/) for parsing arguments.
Update: If the input can't be changed, then I'd suggest working through the list of args and if it starts with a '-' char, remember that option and continue to collect all consecutive options into that array until you reach another flag.
Some rough code:
const opts = {}; // Hold all options
const optionPattern = /^(?<Prefix>-{1,2}|\/)(?<Flag>.*)/; // Support various styles: -s, --s, /s
let currFlag = 'Unknown'; // Bucket to hold any args not specifically marked
for (const elem of process.argv) {
const matchResult = optionPattern.exec(elem);
if (matchResult) {
currFlag = matchResult.groups.Flag;
} else {
opts[currFlag] = opts[currFlag] || []; // Create the array if this is the first one
opts[currFlag].push(elem);
}
}
console.log(`Options Received: ${JSON.stringify(opts, null, 4)}`);
The above would output:
Options Received: {
"Unknown": [
"C:\\Program Files\\nodejs\\node.exe",
"C:\\Projects\\NodeTestScripting\\TestScripts\\CommandLineArgs.js"
],
"s": [
"127.0.0.1:3000"
],
"q": [
"test1.pdf",
"test2.pdf",
"test3.pdf",
"test4.pdf"
],
"v": [
"7"
]
}
Upvotes: 1
Reputation: 2304
You could implement this vary basic solution, iterating through the arguments and picking those which contain ".pdf" in them.
for (i of process.argv) {
if (i.includes(".pdf")) {
//i is your filename now, do something with it
console.log(i);
}
}
Differently, if you don't only have one type of file extension, you could apply a closer solution to what you were already guessing, assuming that the file-names are always contained within the -q
and -v
flags:
let fIdx = process.argv.indexOf('-q');
let vIdx = process.argv.indexOf('-v');
for (i of process.argv.slice(fIdx+1,vIdx)) {
//i is your filename now, do something with it
console.log(i)
}
Upvotes: 1