Reputation: 3984
I am practicing to code in various languages and hence, am a newbie to node.js. The site I am using to practice the code mostly gives me multi-line inputs as an argument to my function, which I don't know how to process (I tried using split on \n, but, that, doesn't work).
Following is a code that, gets multi-line input and then, this input is passed to a function. Can you please tell me how can I read/process the input in-order to store each line of an input in an array as a data item ?
function main(input) {
//Enter your code here
// var arr = input.split("")
process.stdout.write(input[6]);
}
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input;
});
process.stdin.on("end", function () {
main(stdin_input);
});
Thanks'
Upvotes: 5
Views: 5836
Reputation: 751
just a idea my code is just for many string or number have space between for example if you want sum two number we write in terminal : 23 56
notice i use here string_decoder for any one want to raplace number with string
const {StringDecoder} = require('string_decoder');
const decode = new StringDecoder('utf8');
const sum = (a, b) => {
let operation = a + b;
return console.log('result is : ', operation);
}
process.stdin.on('readable', () => {
const aa = process.stdin.read(); // read string from REPL
const buffer = Buffer.from(aa);
const j = decode.write(buffer).split(' ');
const a = +j[0];
const b = +j[1];
// console.log(a + b)
if((a & b) != null) // check if the value not empty
{
sum(a, b);
}
});
Upvotes: 0
Reputation: 1399
Splitting on a new line works for me.
function main(input) {
//Enter your code here
var arr = input.split("\n")
process.stdout.write(JSON.stringify(arr));
}
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input;
});
process.stdin.on("end", function () {
main(stdin_input);
});
It's important to note that process.stdout.write
can only write a string. Trying to pass an array as an argument will cause an error.
Upvotes: 6