Reputation: 97
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?
Upvotes: 0
Views: 262
Reputation: 375
The following npm
packages could help you a lot, and their docs are very great to start with:
Upvotes: 1
Reputation: 1094
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");
Upvotes: 1