You need to sync records.
For a single instance of nodejs, you can use a simple queue, for example:
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(); } } }
In a multi-process instance, you should use some kind of lock, like 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'); }); }
For best performance, you can combine 2 approaches here.
source share