Skip to content
This repository has been archived by the owner on Aug 3, 2022. It is now read-only.

Possible race condition in saveObjectToFile() #22

Open
Soulike opened this issue Nov 30, 2021 · 0 comments
Open

Possible race condition in saveObjectToFile() #22

Soulike opened this issue Nov 30, 2021 · 0 comments

Comments

@Soulike
Copy link

Soulike commented Nov 30, 2021

saveObjectToFile() writes the object to a temporary file first, and then uses asynchronous fs.rename() to move the temporary file to the target file:

fs.writeFile(tmpFileName, json, 'utf8', (err) => {
if (err) return cb(err);
fs.rename(tmpFileName, file, cb);
});
});

If 2 fs.rename()s are called at almost the same time, there will be a race condition, and the execution result is not determined. One of them will lose its operations.

db.save("id", {number: 1}, function (err)
{
    if (err)
    {
        console.error(err);
    }
});

db.save("id", {number: 2}, function (err)
{
    if (err)
    {
        console.error(err);
    }
});

// {"number":1} or {"number":2} in id.json

This problem affects both save() and delete().

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant