Home > OS >  First option should be filled for second option in Node.js
First option should be filled for second option in Node.js

Time:10-14

Codes of global.js file of my global package:

let fileName = '',
    port = '';


newArgv = process.argv.slice(2);

if (newArgv[0] === '-db' && newArgv[1] !== '') {
    fileName = newArgv[1];
} if (newArgv[2] === '-port' && newArgv[3] !== '') {
    port = newArgv[3];
}

jsonSpot(fileName, port);

And jsonSpot(fileName, port); is in another file which is the code below:

myFunction = (entryFileName, entryPort) => {

    let fileName = entryFileName || 'db.json',
        port = entryPort || 4000;

...

I open my CMD and write the command below:

myPackage --db myDb.json --port 3000

And it works.

The command below, works too (port 4000 is considered by default as I've written):

myPackage --db myDb.json

But the another command doesn't and always port 4000 is considered by the rest of my code (here port 3000 should be considered):

myPackage --port 3000

What's the problem with my code?

Is there anything wrong with my commands codes or they are related to other parts (absolutely other parts aren't being shown)?

Thanks

CodePudding user response:

In that case you have only 1 param which is "port", but your code doesn't handle the case where newArgv[0] === '-port'.

Consider using a package like "commander" to handle command line args.

  • Related