gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:08:24 24 4
gpt4 key购买 nike

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

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

最佳答案

也许这对你有帮助。

异步版本:

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)

关于javascript - 如何在 Javascript 中逐行读取文件并将其存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60975836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com