Nodejs:如何优化写入多个文件?
Nodejs: How can I optimize writing many files?
我在 Windows 上的 Node 环境中工作。我的代码每秒接收 30 Buffer
个对象(每个约 500-900kb),我需要尽快将这些数据保存到文件系统,而不参与任何阻止接收以下内容的工作 Buffer
(即目标是保存来自 每个 缓冲区的数据,持续约 30-45 分钟)。就其价值而言,数据是来自 Kinect 传感器的连续深度帧。
我的问题是:在 Node 中写入文件的最佳方式是什么?
这是伪代码:
let num = 0
async function writeFile(filename, data) {
fs.writeFileSync(filename, data)
}
// This fires 30 times/sec and runs for 30-45 min
dataSender.on('gotData', function(data){
let filename = 'file-' + num++
// Do anything with data here to optimize write?
writeFile(filename, data)
}
fs.writeFileSync
似乎比 fs.writeFile
快得多,这就是我在上面使用它的原因。但是有没有其他方法可以对数据进行操作或写入文件来加快每次保存的速度?
我已经编写了一个广泛执行此操作的服务,您可以做的最好的事情是将输入数据直接通过管道传输到文件(如果您也有输入流)。
以这种方式下载文件的简单示例:
const http = require('http')
const ostream = fs.createWriteStream('./output')
http.get('http://nodejs.org/dist/index.json', (res) => {
res.pipe(ostream)
})
.on('error', (e) => {
console.error(`Got error: ${e.message}`);
})
所以在这个例子中没有涉及整个文件的中间复制。当文件从远程 http 服务器以块的形式读取时,它被写入磁盘上的文件。这比从服务器下载整个文件,将其保存在内存中,然后将其写入磁盘上的文件要高效得多。
流是 Node.js 中许多操作的基础,因此您也应该研究它们。
根据您的情况,您应该调查的另一件事是 UV_THREADPOOL_SIZE,因为 I/O 操作使用默认设置为 4 的 libuv 线程池,如果您执行写了很多。
首先,您永远不想使用 fs.writefileSync()
来处理实时请求,因为这会阻塞整个 node.js 事件循环,直到文件写入完成。
好的,基于将每个数据块写入不同的文件,那么您希望允许同时进行多个磁盘写入,但不是无限制的磁盘写入。所以,使用队列还是合适的,但是这次队列不仅仅一次只有一个写入进程,它同时有一定数量的写入进程:
const EventEmitter = require('events');
class Queue extends EventEmitter {
constructor(basePath, baseIndex, concurrent = 5) {
this.q = [];
this.paused = false;
this.inFlightCntr = 0;
this.fileCntr = baseIndex;
this.maxConcurrent = concurrent;
}
// add item to the queue and write (if not already writing)
add(data) {
this.q.push(data);
write();
}
// write next block from the queue (if not already writing)
write() {
while (!paused && this.q.length && this.inFlightCntr < this.maxConcurrent) {
this.inFlightCntr++;
let buf = this.q.shift();
try {
fs.writeFile(basePath + this.fileCntr++, buf, err => {
this.inFlightCntr--;
if (err) {
this.err(err);
} else {
// write more data
this.write();
}
});
} catch(e) {
this.err(e);
}
}
}
err(e) {
this.pause();
this.emit('error', e)
}
pause() {
this.paused = true;
}
resume() {
this.paused = false;
this.write();
}
}
let q = new Queue("file-", 0, 5);
// This fires 30 times/sec and runs for 30-45 min
dataSender.on('gotData', function(data){
q.add(data);
}
q.on('error', function(e) {
// go some sort of write error here
console.log(e);
});
需要考虑的事项:
使用传递给队列构造函数的 concurrent
值进行试验。从 5 的值开始。然后查看将该值提高到更高的值是否会给您带来更好或更差的性能。 node.js 文件 I/O 子系统使用线程池来实现异步磁盘写入,因此存在允许并发写入的最大数量,因此将并发数量提高到非常高可能不会让事情变得更快。
您可以在启动 node.js 应用程序之前通过设置 UV_THREADPOOL_SIZE
环境变量来增加磁盘 I/O 线程池的大小。
你最大的朋友是磁盘写入速度。因此,请确保您有一个具有良好磁盘控制器的快速磁盘。快速总线上的快速 SSD 最好。
如果您可以将写入分散到多个实际物理磁盘上,那也可能会增加写入吞吐量(更多磁盘磁头在工作)。
这是基于对问题的初步解释的先前答案(在编辑更改之前)。
既然你需要按顺序写入磁盘(全部写入同一个文件),那么我建议你要么使用写入流,让流对象为你序列化和缓存数据,要么你可以像这样自己创建一个队列:
const EventEmitter = require('events');
class Queue extends EventEmitter {
// takes an already opened file handle
constructor(fileHandle) {
this.f = fileHandle;
this.q = [];
this.nowWriting = false;
this.paused = false;
}
// add item to the queue and write (if not already writing)
add(data) {
this.q.push(data);
write();
}
// write next block from the queue (if not already writing)
write() {
if (!nowWriting && !paused && this.q.length) {
this.nowWriting = true;
let buf = this.q.shift();
fs.write(this.f, buf, (err, bytesWritten) => {
this.nowWriting = false;
if (err) {
this.pause();
this.emit('error', err);
} else {
// write next block
this.write();
}
});
}
}
pause() {
this.paused = true;
}
resume() {
this.paused = false;
this.write();
}
}
// pass an already opened file handle
let q = new Queue(fileHandle);
// This fires 30 times/sec and runs for 30-45 min
dataSender.on('gotData', function(data){
q.add(data);
}
q.on('error', function(err) {
// got disk write error here
});
您可以使用 writeStream 而不是这个自定义队列 class,但问题是 writeStream 可能会填满,然后您必须有一个单独的缓冲区来放置无论如何数据。像上面那样使用您自己的自定义队列可以同时解决这两个问题。
其他Scalability/Performance 评论
因为您似乎是将数据串行写入同一个文件,您的磁盘写入不会受益于集群或 运行 多个并行操作,因为它们基本上必须被序列化.
如果您的 node.js 服务器除了执行这些写入之外还有其他事情要做,那么创建第二个 node.js 进程并在其他进程中执行所有磁盘写入。您的 node.js 主进程将接收数据,然后将其传递给维护队列并进行写入的子进程。
您可以尝试的另一件事是合并写入。当队列中有多个项目时,您可以将它们组合在一起写入一次。如果写入已经相当大,这可能不会有太大区别,但如果写入很小,这可能会产生很大的不同(将大量小磁盘写入组合成一个较大的写入通常更有效)。
你最大的朋友是磁盘写入速度。因此,请确保您有一个具有良好磁盘控制器的快速磁盘。速度快的 SSD 最好。
我在 Windows 上的 Node 环境中工作。我的代码每秒接收 30 Buffer
个对象(每个约 500-900kb),我需要尽快将这些数据保存到文件系统,而不参与任何阻止接收以下内容的工作 Buffer
(即目标是保存来自 每个 缓冲区的数据,持续约 30-45 分钟)。就其价值而言,数据是来自 Kinect 传感器的连续深度帧。
我的问题是:在 Node 中写入文件的最佳方式是什么?
这是伪代码:
let num = 0
async function writeFile(filename, data) {
fs.writeFileSync(filename, data)
}
// This fires 30 times/sec and runs for 30-45 min
dataSender.on('gotData', function(data){
let filename = 'file-' + num++
// Do anything with data here to optimize write?
writeFile(filename, data)
}
fs.writeFileSync
似乎比 fs.writeFile
快得多,这就是我在上面使用它的原因。但是有没有其他方法可以对数据进行操作或写入文件来加快每次保存的速度?
我已经编写了一个广泛执行此操作的服务,您可以做的最好的事情是将输入数据直接通过管道传输到文件(如果您也有输入流)。 以这种方式下载文件的简单示例:
const http = require('http')
const ostream = fs.createWriteStream('./output')
http.get('http://nodejs.org/dist/index.json', (res) => {
res.pipe(ostream)
})
.on('error', (e) => {
console.error(`Got error: ${e.message}`);
})
所以在这个例子中没有涉及整个文件的中间复制。当文件从远程 http 服务器以块的形式读取时,它被写入磁盘上的文件。这比从服务器下载整个文件,将其保存在内存中,然后将其写入磁盘上的文件要高效得多。
流是 Node.js 中许多操作的基础,因此您也应该研究它们。
根据您的情况,您应该调查的另一件事是 UV_THREADPOOL_SIZE,因为 I/O 操作使用默认设置为 4 的 libuv 线程池,如果您执行写了很多。
首先,您永远不想使用 fs.writefileSync()
来处理实时请求,因为这会阻塞整个 node.js 事件循环,直到文件写入完成。
好的,基于将每个数据块写入不同的文件,那么您希望允许同时进行多个磁盘写入,但不是无限制的磁盘写入。所以,使用队列还是合适的,但是这次队列不仅仅一次只有一个写入进程,它同时有一定数量的写入进程:
const EventEmitter = require('events');
class Queue extends EventEmitter {
constructor(basePath, baseIndex, concurrent = 5) {
this.q = [];
this.paused = false;
this.inFlightCntr = 0;
this.fileCntr = baseIndex;
this.maxConcurrent = concurrent;
}
// add item to the queue and write (if not already writing)
add(data) {
this.q.push(data);
write();
}
// write next block from the queue (if not already writing)
write() {
while (!paused && this.q.length && this.inFlightCntr < this.maxConcurrent) {
this.inFlightCntr++;
let buf = this.q.shift();
try {
fs.writeFile(basePath + this.fileCntr++, buf, err => {
this.inFlightCntr--;
if (err) {
this.err(err);
} else {
// write more data
this.write();
}
});
} catch(e) {
this.err(e);
}
}
}
err(e) {
this.pause();
this.emit('error', e)
}
pause() {
this.paused = true;
}
resume() {
this.paused = false;
this.write();
}
}
let q = new Queue("file-", 0, 5);
// This fires 30 times/sec and runs for 30-45 min
dataSender.on('gotData', function(data){
q.add(data);
}
q.on('error', function(e) {
// go some sort of write error here
console.log(e);
});
需要考虑的事项:
使用传递给队列构造函数的
concurrent
值进行试验。从 5 的值开始。然后查看将该值提高到更高的值是否会给您带来更好或更差的性能。 node.js 文件 I/O 子系统使用线程池来实现异步磁盘写入,因此存在允许并发写入的最大数量,因此将并发数量提高到非常高可能不会让事情变得更快。您可以在启动 node.js 应用程序之前通过设置
UV_THREADPOOL_SIZE
环境变量来增加磁盘 I/O 线程池的大小。你最大的朋友是磁盘写入速度。因此,请确保您有一个具有良好磁盘控制器的快速磁盘。快速总线上的快速 SSD 最好。
如果您可以将写入分散到多个实际物理磁盘上,那也可能会增加写入吞吐量(更多磁盘磁头在工作)。
这是基于对问题的初步解释的先前答案(在编辑更改之前)。
既然你需要按顺序写入磁盘(全部写入同一个文件),那么我建议你要么使用写入流,让流对象为你序列化和缓存数据,要么你可以像这样自己创建一个队列:
const EventEmitter = require('events');
class Queue extends EventEmitter {
// takes an already opened file handle
constructor(fileHandle) {
this.f = fileHandle;
this.q = [];
this.nowWriting = false;
this.paused = false;
}
// add item to the queue and write (if not already writing)
add(data) {
this.q.push(data);
write();
}
// write next block from the queue (if not already writing)
write() {
if (!nowWriting && !paused && this.q.length) {
this.nowWriting = true;
let buf = this.q.shift();
fs.write(this.f, buf, (err, bytesWritten) => {
this.nowWriting = false;
if (err) {
this.pause();
this.emit('error', err);
} else {
// write next block
this.write();
}
});
}
}
pause() {
this.paused = true;
}
resume() {
this.paused = false;
this.write();
}
}
// pass an already opened file handle
let q = new Queue(fileHandle);
// This fires 30 times/sec and runs for 30-45 min
dataSender.on('gotData', function(data){
q.add(data);
}
q.on('error', function(err) {
// got disk write error here
});
您可以使用 writeStream 而不是这个自定义队列 class,但问题是 writeStream 可能会填满,然后您必须有一个单独的缓冲区来放置无论如何数据。像上面那样使用您自己的自定义队列可以同时解决这两个问题。
其他Scalability/Performance 评论
因为您似乎是将数据串行写入同一个文件,您的磁盘写入不会受益于集群或 运行 多个并行操作,因为它们基本上必须被序列化.
如果您的 node.js 服务器除了执行这些写入之外还有其他事情要做,那么创建第二个 node.js 进程并在其他进程中执行所有磁盘写入。您的 node.js 主进程将接收数据,然后将其传递给维护队列并进行写入的子进程。
您可以尝试的另一件事是合并写入。当队列中有多个项目时,您可以将它们组合在一起写入一次。如果写入已经相当大,这可能不会有太大区别,但如果写入很小,这可能会产生很大的不同(将大量小磁盘写入组合成一个较大的写入通常更有效)。
你最大的朋友是磁盘写入速度。因此,请确保您有一个具有良好磁盘控制器的快速磁盘。速度快的 SSD 最好。