作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个文件,其中的数据格式如下
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/
我是一名优秀的程序员,十分优秀!