For This
For This

Reputation: 173

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

Upvotes: 4

Views: 2472

Answers (2)

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)

Upvotes: 5

Nilanka Manoj
Nilanka Manoj

Reputation: 3738

You can directly use line-reader :

fileData.js :

const lineReader = require('line-reader');
class FileData {

    constructor(filePath) {
        this.emails = [];
        this.names = [];

        lineReader.eachLine(filePath, function(line) {
            console.log(line);
            const splitedLine = line.split(':');
            emails.push(splitedLine[0]);
            names.push(splitedLine[1]);
        });
    }

    getEmails(){
        return this.emails;
    }

    getNames(){
        return this.names;
    }   


}

module.exports = FileData

Whrerever You want:

const FileData = require('path to fileData.js');
const fileData = new FileData('test.txt');
console.log(fileData.getEmails())

Upvotes: 0

Related Questions