javascript - 如何在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);
}
解决方案
也许这会对你有所帮助。
异步版本:
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)
推荐阅读
- vb.net - 如何使用 Visual Basic 在列表视图中计算价格列的总和
- python - 如何更改列中的特定值
- c++ - 将 ifstream 读取为 char* 以进行 int 和 string 转换
- visual-studio-code - vscode:无法连接到远程机器vai Remote-SSH
- scala - 如何转换为元组并提高 1 行 SQL 请求的性能?
- java - 如何在java 8中获得两个不同类的内连接结果
- python - 为什么我得到 AttributeError: 'Variable' object has no attribute '__dict__' 使用 pickle.loads 时?
- kubernetes - Istio tls 端口 443 给出 503 Service Unavailable
- c++ - 故意泄漏 std::vector 的内存
- java - 如果找到特定数字,如何使此打印为真或假?