【问题标题】:Reading lines of .txt file with Javascript (Node.js)使用 Javascript (Node.js) 读取 .txt 文件的行
【发布时间】:2020-09-04 14:38:47
【问题描述】:



我是 JavaScript 竞争性编程的新手,我想知道如何在函数中提供输入文本和 如何使用它(如果可能的话,了解最新的语法)
这是我的 input.txt =>

5
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676

这是我的 Javascript(Node.js) 样板代码:

process.stdin.resume();         // I supose this reads the file it's beeing passed .txt => .js
process.stdin.setEncoding("ascii"); 
_input = "";
process.stdin.on("data", function (input) {
    _input += input;            // this adds up each character/line(?) it reads to the _input variable
});

process.stdin.on("end", function () {
   processData(_input);         // And finally sends the input multiple times(?) (I guess)
});

function processData(input) {
    console.log(input)          // Because the input will only log the first line of the input.txt file (5)

    // I'd like to:
      // 1) Be able to perform my algorithm using line by line input
      // 2) Be able to gather multiple lines (of my choice) before performing my argorithm, 
         // let's say store multiple lines of input in an array like arr = ['line1', 'line2', 'line3'...]
} 

感谢您帮助我理解。 来源:https://www.hackerrank.com/contests/projecteuler/challenges/euler013/problem

【问题讨论】:

    标签: javascript node.js algorithm


    【解决方案1】:

    原来输入是一个用“\n”分隔的字符串,console.log() 在每一行都打断,这意味着它只会显示第一行。

    process.stdin.resume();         
    process.stdin.setEncoding("ascii"); 
    _input = "";
    process.stdin.on("data", function (input) {
        _input += input;            
    });
    
    process.stdin.on("end", function () {
       processData(_input);         
    });
    
    function processData(input) {
    
        console.log(input)        // => 5
    
        input = input.split("\n");
    
        console.log(input)        // will show the input (array) =>   [ '5',
    //                            '37107287533902102798797998220837590246510135740250',
    //                            '46376937677490009712648124896970078050417018260538',
    //                            '74324986199524741059474233309513058123726617309629',
    //                            '91942213363574161572522430563301811072406154908250',
    //                            '23067588207539346171171980310421047513778063246676' ]
    
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多