Javascript(Node.js)-如何读取和处理作为函数输入提供的多行代码?

sul*_*edi 4 javascript node.js

我正在练习使用各种语言编写代码,因此是Node.js的新手。我用来练习代码的站点主要为我提供了多行输入作为函数的参数,我不知道该如何处理(我尝试在\ n上使用split,但这是行不通的) 。

以下是获得多行输入的代码,然后将该输入传递给函数。您能告诉我如何读取/处理输入以便将输入的每一行作为数据项存储在数组中吗?

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);
});
Run Code Online (Sandbox Code Playgroud)

谢谢'

Ben*_*ick 5

换行适合我。

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);
});
Run Code Online (Sandbox Code Playgroud)

重要的是要注意process.stdout.write只能写一个字符串。尝试将数组作为参数传递将导致错误。