Home > database >  How to store data from reading lines in nodejs
How to store data from reading lines in nodejs

Time:05-22

Hello I have external txt file with data to my function. How can I store read line to variable

const fs = require("fs");
const readline = require("readline");
const firstVariable; [it is firstLine]
const secondVariable; [it is secondLine]
const thirdVariable; [it is thirdLine]
const fourthVariable; [it is fourthLine]

const readInterface = readline.createInterface({
  input: fs.createReadStream("./slo1.in"),
  output: process.stdout,
  terminal: false,
});

readInterface.on("line", function (line) {
  console.log(line);
});

CodePudding user response:

Here is a better solution:

const fs = require("fs");
const readline = require("readline");

const readFile = () => {
return new Promise((resolve, reject) => {
    const lineArray = [];
    const readInterface = readline.createInterface({
        input: fs.createReadStream("./slo1.in"),
        output: process.stdout,
        terminal: false,
    });

    readInterface.on("line", (line) => {
        lineArray.push(line);
    }).on("close", () => {
        resolve(lineArray);
    });
})
}



readFile().then(res => {
    console.log(JSON.stringify(res))
})


// or you can use async/await syntax
async function readAsync() {
    const res = await readFile();
    console.log(res)
}

readAsync();

  • Related