0

I have two JavaScript file for reading and writing a common text file. Created a task scheduler to run this JavaScript file at same time. So i need to implement lock concept in scripts. Is there exists any lock concept in JavaScript ?

More Clarification on Question:

I am not using node.js. simply it is a jscript file.

There is two Jscript file, File A and File B.

Both files are configured by a task scheduler at a time 10 am.

Both files are reading a text file D.Updates some text and write again to it.

If there occurs any resource starvation like, File A and File B are writing text file D at same time but different content.

try {
    var objectFile = new ActiveXObject("Scripting.FileSystemObject");
    var writingFile;

    if(objectFile.FileExists(FileLocation))
    {
        var fileSpecified = objectFile.GetFile(FileLocation);
        writingFile = fileSpecified.OpenAsTextStream( 8, 0 );
    }

    else
    {
        writingFile= objectFile.CreateTextFile(FileLocation, true);
    }

    writingFile.WriteLine(Date());

    writingFile.WriteLine("test data");     

    writingFile.Close();
}
catch(e)
{
    return true;
}
RPichioli
  • 3,245
  • 2
  • 25
  • 29

1 Answers1

0

The FileSystemObject does not support file locking. The best you can do is to delete the file before writing. Note that initially you have to create an empty file at FileLocation.

try {
    var fso = new ActiveXObject("Scripting.FileSystemObject");

    try {
      fso.DeleteFile(FileLocation); // Will throw if file does not exist
      var writingFile= fso.CreateTextFile(FileLocation);
      writingFile.WriteLine(Date());
      writingFile.WriteLine("test data");     
      writingFile.Close();
    } catch(e) {
      // File did not exist, so somebody is currently writing it.
    }
}
catch(e)
{
    return true;
}

There is also the append-trick, see See also How can I determine if a file is locked using VBS?. But this is not save to use if you do not want to append.

Community
  • 1
  • 1
Wolfgang Kuehn
  • 12,206
  • 2
  • 33
  • 46