0

I want to write some command with some args (for example /add 5 5 and it will print 10) in console when program is already running. How should I do it?

irqize
  • 97
  • 1
  • 10
  • http://stackoverflow.com/questions/4351521/how-to-pass-command-line-arguments-to-node-js – Ido Dec 11 '15 at 17:33
  • I don't mean to launch the app with some arguments, but to write a command during program execution – irqize Dec 11 '15 at 17:42

2 Answers2

1

How to read from console is already explained in this answer, so I'll just show you how to parse those lines.

Example approach is to create object with references to your functions, and then call them by name, after parsing input string.

My example uses Spread Operator and let which need running script in strict mode ( "use strict"; ).

Example's code:

"use strict";

var funs = {};

funs.add = function add (x, y) {
  if( x === undefined || y === undefined ) {
    console.log("Not enough arguments for add!");
    return;
  }
  console.log("Result:", (+x) + (+y));
}

function parseInput(input) {
  if( input.charAt(0) === "/" ) {
    let tmp = input.substring(1);
    tmp = tmp.split(" ");
    let command = tmp[0];
    let args = tmp.slice(1);

    let fun = funs[command];

    if ( fun === undefined ) {
      console.log(command, "command is not defined!");
      return;
    }
    fun(...args);
  }
}

parseInput("/add 5 6");
Community
  • 1
  • 1
Marqin
  • 1,096
  • 8
  • 17
1

The following npm packages could help you a lot, and their docs are very great to start with:

mkinawy
  • 375
  • 1
  • 10