trzeba zsynchronizować zapisy.
Dla jednej instancji nodejs można użyć prostego kolejkę, tak:
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.unshift();
cb(err);
});
}
add (...args) {
this.queue.push(...args);
if (this.queue.length === 1) {
this.next();
}
}
}
W multi-proces instancja trzeba użyć jakiś zamek, na przykład z 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');
});
}
Dla lepszej wydajności można nawet połączyć 2 podejścia tutaj.
spróbuj pisać jako metody synchronizacji –