javascript - 我如何使用 fs 或不使用 fs 读取文件,但我想读取每行的行?

我想用 fs 读取文件,但到目前为止我做不到,从不显示控制台 2222,为什么看不到控制台?

const inputFileName = "./input.txt";

fs.createWriteStream(outputFileName, { flags: "a" });
const fileStream = fs.createReadStream(inputFileName);
const file =  readline.createInterface({
  input: fileStream,
  crlfDelay: Infinity,
});

for await (const row of file) {
    console.log(2222)
  }

或者我如何在没有 fs 的情况下阅读,不介意,但我需要每行一行

回答1

你应该听 line 事件。这是一个简单的代码。

let fs = require('fs');
let readline = require('readline');

let strInputFileName = 'input.txt';

let fRead = fs.createReadStream(strInputFileName); 
  
fRead.on('end', ()=>{ 
    console.log('end'); 
}); 
  
let objReadline = readline.createInterface({ 
    input: fRead, 
}); 

objReadline.on('line', (strLine)=>{ 
    console.log(strLine)
});

回答2

在这里你可以去

function readTextFile(file) {
        var rawFile = new XMLHttpRequest(); 
        rawFile.open("GET", file, false); // open with method GET the file with the 
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
            {
                if(rawFile.status === 200) // status 200: "OK"
                {
                    var allText = rawFile.responseText; //  Returns the response data 
                     var str_array = allText.split('\n'); //convert to array

                     // use map function
                     str_array.map((value, key)=> {
                        console.log(value); //row per row data
                     })
                }
            }
        }
        rawFile.send(null); //Sends the request to the server Used for GET requests with param null
    }

    readTextFile("demo.txt"); //pass the file path

相似文章

随机推荐

最新文章