I am starting off withe nodeJS. Here is my code
function ask(callback) {
var stdin = process.stdin, stdout = process.stdout;
stdin.resume();
stdin.once('data', function(data) {
data = data.toString().trim();
callback(data);
});
}
ask(function(testcase) {
ask(function(workers) {
ask(function(salary) {
console.log(salary);
});
});
});
What i would like to do is based on the first input i,e testcase .I would like to run a for loop around the two ask(function(workers)) and ask(function(salary))
eg input
2 -- two testcases
2 - num of workers
1 2 - salary / first testcase over
3 - num of workers
1 2 3 - salary / second - testcase over
Now start processing the input. I know nodeJS is aysnchronus and hence even if i place a for loop after the first ask(function(testcase)) . It does not work.
Can anyone guide me as to how to accept inputs in a synchronous manner.
I would do it this way:
function test(testcase) {
ask(function(workers) {
ask(function(salary) {
console.log(salary);
// Do whatever you want with the data
// Then:
ask(test);
});
});
}
ask(test);
There is no synchronous IO API for the standard input. However, you could read the whole input into a string (until EOF appears), and then process the string in a synchronous manner.