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?

2
  • stackoverflow.com/questions/4351521/… Commented Dec 11, 2015 at 17:33
  • I don't mean to launch the app with some arguments, but to write a command during program execution Commented Dec 11, 2015 at 17:42

2 Answers 2

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");
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.