如何使用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');
    });
}

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

10-06 09:09
查看更多