簡體   English   中英

使用 Javascript (Node.js) 讀取 .txt 文件的行

[英]Reading lines of .txt file with Javascript (Node.js)



我是 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

事實證明,輸入是一個以“\\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' ]

} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM