batman
batman

Reputation: 4908

Files is deleting before its used in node js

I'm new to node js and i'm trying to do the following:

function createPasswordfile(content)
{
    fs.writeFile(passwordFileName,content, function(err) {
        if(err) {
            console.log("Failed on creating the file " + err)
        } 
    });

    fs.chmodSync(passwordFileName, '400');
}

function deletePasswordFile()
{
    fs.chmodSync(passwordFileName, '777');
    fs.unlink(passwordFileName,function (err) {
      if (err) throw err;
      console.log('successfully deleted');
    });
}

and there are three statements which call these functions:

createPasswordfile(password)
someOtherFunction() //which needs the created password file
deletePasswordFile()

The problem I'm facing is when I add the deletePasswordFile() method call, I get error like this:

Failed on creating the file Error: EACCES, open 'password.txt'
successfully deleted

Since its non blocking, I guess the deletePasswordFile function deletes the file before other function make use of it.

If deletePasswordFile is commented out, things are working fine.

How should I prevent this?

Upvotes: 1

Views: 64

Answers (1)

Jivings
Jivings

Reputation: 23250

writeFile is asynchronous, so it's possible the file is still being written when you try and delete it.

Try changing to writeFileSync.

fs.writeFileSync(passwordFileName, content);

Upvotes: 1

Related Questions