-1

My Node.js script is running differently between the command line and from within a bash script. Everything works normally via the command line, but the second argument is not being recognized when run from within the bash script.

Do I need to pass the arguments differently inside the bash script?

server.js is provided two arguments:
1. Command (in this case, update a table via mySQL)
2. Table (desired table to update via data pulled from API)

Command Line/Script Entry:

node server.js -update-table table1

server.js:

var args          = process.argv.slice(2);
var command       = args[0];

switch (command) {
  case '-update-table':
    var tableName = args[1];
    switch (tableName) {
      case 'table1':
           tableUpdateFunction.table1();
           break;

      case 'table2':
           tableUpdateFunction.table2();
           break;

      default:
           console.log('ERROR: Unknown Table Name ' + tableName)
           break;
    }
    break;
}

Console When Run from Script (Triggers Default Case):

ERROR: Unknown Table Name table1
  • can you post your script? – Gobind Deep Singh Oct 19 '19 at 16:33
  • Print type of `tableName` with `console.log(typeof tableName)` in default case. – hoangdv Oct 19 '19 at 16:34
  • [This answer](https://stackoverflow.com/a/14910812/7400903) will explain your issue. And I don't see why anyone would downvote your question, because it is seemingly in place (the printout requires some thinking over it). – goodvibration Oct 19 '19 at 16:37
  • @goodvibration: How does your linked answer explain the issue? The linked answer is about an aspect of jQuery's `each`. – rici Oct 19 '19 at 17:15

1 Answers1

0

I think it's likely that you're running into a Windows line-ending problem. If you prepared your script file using some Windows utility, and then invoke it in a Unix-like environment, the fact that the command line is terminated with a CR-LF sequence (Windows) will cause problems with a shell compiled for use in a unix environment, because the CR will be treated as an ordinary character.

That's a bit hard to see because the CR is totally invisible at the end of a line, and only visible for its effect in other contexts. You can make the CR visible by making sure that the text you substitute in any output has some following visible character. For example, if you changed the error report to:

console.log('ERROR: Unknown Table Name "' + tableName + "'")

then you might see this:

"RROR: Unknown Table Name "table1

Note that the E in ERROR has been overwritten with a double quote; that's because the CR at the end of table1 causes the cursor to move back to the left-hand margin before the following " is printed.

rici
  • 234,347
  • 28
  • 237
  • 341