Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to store data from reading lines in nodejs

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);
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading