Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file line by line in Javascript and store it in an array

I have a file in which the data is in the form like

[email protected]:name
[email protected]:nameother
[email protected]:onemorename

I want to store the emails and names in arrays like

email = ["[email protected]","[email protected]","[email protected]"]

names = ["name","nameother","onemorename"]

Also, guys, the file is a little bit large around 50 MB so also I want to do it without using a lot of resources

I have tried this to work but can't make things done

    // read contents of the file
    const data = fs.readFileSync('file.txt', 'UTF-8');

    // split the contents by new line
    const lines = data.split(/\r?\n/);

    // print all lines
    lines.forEach((line) => {
       names[num] = line;
        num++
    });
} catch (err) {
    console.error(err);
}
like image 708
For This Avatar asked Sep 18 '25 20:09

For This


1 Answers

Maybe this will help you.

Async Version:

const fs = require('fs')

const emails = [];
const names = [];

fs.readFile('file.txt', (err, file) => {

  if (err) throw err;

  file.toString().split('\n').forEach(line => {
    const splitedLine = line.split(':');

    emails.push(splitedLine[0]);
    names.push(splitedLine[1]);

  });
});

Sync Version:

const fs = require('fs')

const emails = [];
const names = [];

fs.readFileSync('file.txt').toString().split('\n').forEach(line => {
  const splitedLine = line.split(':');

  emails.push(splitedLine[0]);
  names.push(splitedLine[1]);
})

console.log(emails)
console.log(names)
like image 98
אברימי פרידמן Avatar answered Sep 21 '25 11:09

אברימי פרידמן