如何在Javascript中逐行读取文件并将其存储在数组中

For*_*his 2 javascript node.js

我有一个文件,其中数据的格式如下

abc@email.com:name
ewdfgwed@gmail.com:nameother
wertgtr@gmsi.com:onemorename
Run Code Online (Sandbox Code Playgroud)

我想将电子邮件和姓名存储在数组中,例如

email = ["abc@email.com","ewdfgwed@gmail.com","wertgtr@gmsi.com"]

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

另外,伙计们,文件有点大,大约 50 MB,所以我也想在不使用大量资源的情况下完成

我已经尝试过这个工作,但无法完成任务

    // 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);
}
Run Code Online (Sandbox Code Playgroud)

אבר*_*דמן 5

也许这会帮助你。

异步版本:

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

  });
});
Run Code Online (Sandbox Code Playgroud)

同步版本:

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)
Run Code Online (Sandbox Code Playgroud)