When running a program with node:
node test.js
How do you check if the program is given an ARGV
when run node test.js --example
? What I've tried so far is the following:
function say(input){
console.log(input);
}
if(process.argv[1] !== '')
{
say('false');
}
else {
say('success');
}
if(process.argv[1] === null)
{
say('false');
}
else {
say('success');
}
However the first solution won't output the else
and the second solution only outputs NUL is not defined
so with that, what I'm thinking is that I'm making some mistake in my coding?
try this to be very well aware :
console.log(process.argv);
Thanks to the answer provided by kevin ternet, and for the information provided by maioman what I ended up doing was this:
if(process.argv[2] === undefined){
say('false');
} else {
say('true');
}
Here's what happens when you process ARGV
in Node:
ARGV[0]
:
if(process.argv[0] === undefined){
console.log('Failure');
console.log(process.argv[0]);
} else {
console.log('Success');
console.log(process.argv[0]);
}
Output:
Success
C:\Program Files\nodejs\node.exe //Path to node executable
ARGV[1]
:
if(process.argv[1] === undefined){
console.log('Failure');
console.log(process.argv[1]);
} else {
console.log('Success');
console.log(process.argv[1]);
}
Output:
Success
C:\Users\bin\javascript\node\test.js //Path to file
ARGV[2]
:
if(process.argv[2] === undefined){
console.log('Failure');
console.log(process.argv[1]);
} else {
console.log('Success');
console.log(process.argv[2]);
}
Output:
Success
--example //The actual flag that was given
So therefore to check if a flag is actually given, you look for ARGV[2]
.
Here's an example of the entire ARGV
tree ran:
if(process.argv === undefined){
console.log('Failure');
console.log(process.argv);
} else {
console.log('Success');
console.log(process.argv);
}
Success
[ 'C:\\Program Files\\nodejs\\node.exe' //ARGV[0],
'C:\\Users\\bin\\javascript\\node\\test.js' //ARGV[1],
'--example' //ARGV[2] ]
So as you can see the tree is structured as an array, with the first argument being 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With