Skip to content

Commit

Permalink
[FileSystem] Call all write (save method) callbacks when before remov…
Browse files Browse the repository at this point in the history
…e the queue.
Sediug committed May 25, 2018
1 parent 74eefc0 commit fa7a091
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions lib/storage/filesystem.js
Original file line number Diff line number Diff line change
@@ -16,6 +16,7 @@ const fileSystem = {
* @param {object} defaults Default value if it has to create the file.
* @param {function} cb Callback called when file readed. Takes two arguments, the first
* one is the error (if any) and the second one is the file content.
* @returns {void} Nothing.
*/
function read(file, defaults, cb) {
try {
@@ -40,27 +41,25 @@ function read(file, defaults, cb) {
* @param {object} db Data to store into the file.
* @param {function} cb Callback called when file readed. Takes one argument, the error
* (if any).
* @returns {void} Nothing.
*/
function save(file, db, cb) {
// Race condition - https://github.com/nodejs/node-v0.x-archive/issues/3958
// Save only last call.
const saving = writeQueue[file] !== undefined;
writeQueue[file] = { db, cb };

if (saving) {
if (writeQueue[file]) {
writeQueue[file].db = db;
writeQueue[file].callbacks.push(cb);
return;
} else {
writeQueue[file] = { callbacks: [cb], db };
}

// If not already saving then save, but using the object we make sure to take only
// the last changes.
// Truncate - https://stackoverflow.com/questions/35178903/overwrite-a-file-in-node-js
fs.truncate(file, err => {
fse.outputJson(file, writeQueue[file].db, err => {
if (err) {
writeQueue[file].cb(err);
}

writeQueue[file].cb();
resolveAllWriteQueueCallbacks(file, err);
delete writeQueue[file];
});
});
@@ -74,6 +73,7 @@ function save(file, db, cb) {
* @param {object} defaults Default value if it has to create the file.
* @param {function} cb Callback called when the path existance was validated. Takes one
* argument, the error (if any).
* @returns {void} Nothing.
*/
function ensure(file, defaults, cb) {
fse.pathExists(file, (err, exists) => {
@@ -89,4 +89,15 @@ function ensure(file, defaults, cb) {
});
}

/**
* Internal. Call to every callback of a the write queue for a file.
*
* @param {string} file File path .
* @param {string} error Error message or null.
* @returns {void} Nothing.
*/
function resolveAllWriteQueueCallbacks(file, error) {
writeQueue[file].callbacks.forEach(cb => cb(error));
}

module.exports = fileSystem;

0 comments on commit fa7a091

Please sign in to comment.