gpt4 book ai didi

node.js - 如何使用 socket.io 处理 Node 服务器上的并发文件写入请求

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:38 24 4
gpt4 key购买 nike

如何使用 socket.io 处理 Node 服务器上的并发文件写入请求。我正在用它来写:

fs.writefile('abc.txt','datatobewritten','utf8',function(err){});

我有一个文件 abc.txt,假设两个用户试图同时在这个文件上写,然后我收到一个错误,那么我该如何排队多个请求。

最佳答案

您必须同步写入。

对于单个 nodejs 实例,您可以使用简单的队列,如下所示:

module.exports = function(path, content, cb){
var queue = queues[path];
if (queue == null)
queue = queues[path] = new Queue;

queue.add(path, content, (err) => {
cb(err);
queue.next();
});
};

var fs = require('fs');
var queues = {};

class Queue {
constructor () {
this.queue = [];
}
next () {
if (this.queue.length === 0)
return;

var [path, content, cb] = this.queue[0];
fs.writeFile(path, content, 'utf8', (err) => {
this.queue.shift();
cb(err);
});
}
add (...args) {
this.queue.push(args);
if (this.queue.length === 1) {
this.next();
}
}
}

多进程 实例中你必须使用一些锁定,例如 lockfile .

var lockFile = require('lockfile');
var fs = require('fs');


module.exports = function(path, content, cb) {
lockFile.lock('foo.lock', function (err) {
if (err) return cb(err);

fs.writeFile(path, content, cb);
lockFile.unlock('foo.lock');
});
}

为了获得更好的性能,您甚至可以在此处组合两种方法。

关于node.js - 如何使用 socket.io 处理 Node 服务器上的并发文件写入请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36010450/

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