首页 > 解决方案 > 如何在Javascript中逐行读取文件并将其存储在数组中

问题描述

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

abc@email.com:name
ewdfgwed@gmail.com:nameother
wertgtr@gmsi.com:onemorename

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

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

标签: javascriptnode.js

解决方案


也许这会对你有所帮助。

异步版本:

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

  });
});

同步版本:

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)

推荐阅读