Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if ARGV is given when running a program with node

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?

like image 717
13aal Avatar asked Dec 25 '22 05:12

13aal


2 Answers

  • argv[0] is the name of your node inerpretor --> in general node
  • argv[1] is the path to your script. So argv[1] is always filled

try this to be very well aware :

console.log(process.argv);
like image 132
kevin ternet Avatar answered Dec 26 '22 20:12

kevin ternet


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.

like image 27
13aal Avatar answered Dec 26 '22 19:12

13aal