如何使用socket.io处理节点服务器上的并发文件写入请求 [英] How to handle concurrent file write requests on a node server with socket.io

查看:97
本文介绍了如何使用socket.io处理节点服务器上的并发文件写入请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to handle concurrent file write requests on a node server with socket.io. I am using this to write:

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

我有一个文件abc.txt,并且假设有两个用户尝试同时在该文件上写东西,然后出现错误,因此如何将多个请求排队.

I have a file abc.txt and suppose two users try to write on the same time on this file then I am getting an error, so how do I queue multiple requests.

推荐答案

您必须同步写入.

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

For a single instance of nodejs you can use simple queue, like this:

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 .

In multi-process instance you have to use some locking, for example with 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');
    });
}

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

这篇关于如何使用socket.io处理节点服务器上的并发文件写入请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆