【发布时间】:2019-01-08 05:39:55
【问题描述】:
我一直在尝试优化使用 node 读取非常大的文件并开始遇到瓶颈,所以我想我会尝试使用 node 中的线程。
我正在尝试读取 2 个文件
包含 1000 - 100,000 个 uuid 的针我正在尝试查找我正在读取同步并拆分文件。
事先不知道行数。
包含数亿行 uuid 大小为 3.4gb+ 的 haystack 我想按读取量拆分它并拆分文件的读取。
// example needle.txt/haystack.txt
a57a258d-7e56-40e1-962e-d683a17d7d3b
4380b26b-36d3-4cfe-ae3b-9121bf1f0c12
ebda3a08-857f-41d2-99bf-a288f0470af8
process.argv[3] 是针,process.argv[4] 是草垛,我也可以接受来自process.stdin 的草垛
我正在努力解决的是如何在保留文件行的同时处理拆分文件,这可能吗?
#!/usr/bin/env node
const fs = require('fs');
const cluster = require('cluster');
const { createInterface } = require('readline');
if (cluster.isMaster) {
const fileSize = fs.statSync(process.argv[4]).size;
const threads = 4;
const n = new Set(
fs
.readFileSync(process.argv[3])
.toString()
.split('\n')
);
for (var i = 0; i < threads; i++) {
const buffer = {};
const worker = cluster.fork();
worker.on('message', function(lines) {
// main thread received buffer from thread
/*
how to combine the data so i can read the lines
if (n.has(line)) {
console.log(line)
}
*/
});
worker.on('exit', threadNum => {
// exited thread all parts read from that thread
})
worker.send({start: i * (fileSize / threads), end: (i + 1) * (fileSize / threads), i});
}
} else {
process.on('message', function({ start, end, i }) {
/*
worker code here we start streaming from one part of the file
to another
*/
createInterface({
input: fs.createReadStream(process.argv[4], {
start,
end
})
})
.on('line', data => {
// sending data back to main thread with thread number
process.send({data, thread: i});
})
.on('close', () => process.exit(i))
});
}
是否可以告诉 readline.createInterface 继续阅读直到它遇到一个字符?我可以通过传递线程号并在主线程中拆分来组合缓冲区吗?
任何帮助将不胜感激。
如果有人想知道我正在运行 cmd
node index.js --needles needles.txt haystack.txt
【问题讨论】:
-
您是否考虑过为文件创建 readStream 然后处理数据块?
-
是的,是的,我已经完成了,我正在尝试通过线程来优化它,因为我得到的速度并不是那么好
-
在下面回答,看看吧
标签: javascript node.js stream buffer