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

4
我有一个文件,其中的数据形式如下:
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);
}

你可以先看一下 splitmap。使用这两个工具,你几乎可以完成整个任务。你可能需要类似 textVariable.split(/[\r\n]+/) 这样的代码来获取行数组,然后可以使用 .map 来获取冒号前或后的内容。也许你可以试一试,如果遇到问题,就发布你的代码并寻求帮助? - David784
1
欢迎,@For This!请务必阅读“如何提问”部分:https://stackoverflow.com/help/how-to-ask。由于这似乎不是在询问具体问题,而是在请求别人为您编写代码,因此很可能会被关闭。尝试包含您已经尝试过的内容,您认为可能有效但实际上并没有...等等。 - Dave
2
请检查[mcve]并分享您已尝试的示例。 - nircraft
1
这个回答解决了你的问题吗?在node.js中逐行读取文件? - Cameron Little
2个回答

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

  });
});

同步版本:

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)

我不知道为什么,但当我尝试运行console.log emails[0]时,它返回未定义,但我想要它的值。 - For This
我相信你把"console.log"放在了最后一行。 fs.readFile()是异步的。 把"console.log"放在括号里面。 - אברימי פרידמן
嗯,但我希望可以在括号外访问它。 - For This
是的,但我需要在括号外访问它,这是主要问题。 - For This
我改变了我的答案。你可以使用同步版本。 - אברימי פרידמן

0

您可以直接使用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

无论您想在哪里:

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

这里的问题是我只能在函数内部访问这些值,但我想在全局范围内使用它。 - For This

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接