简体   繁体   中英

Javascript (Node.js) - How to read and process multiple line provided as an input to a function?

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'

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.

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);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM