如何在NodeJS中使用文本文件时有效地锁定它?

时间:2019-01-23 04:25:49

标签: javascript node.js lockfile

我有几个独立的脚本,可以从同一文本文件读取和写入。我正在尝试在模块从中读取/写入文本文件时锁定它们。目前,我正在使用lockfile包,但它似乎无法正常工作。例如

//lock file before reading

lockFile.lockSync("./Config/presetString.txt.lock",10000,100,10000,1000,100)

//read file

var preset = fs.readFileSync("./Config/presetString.txt", 'utf8');

//unlock file

lockFile.unlockSync("./Config/presetString.txt.lock",10000,100,10000,1000,100)

但是,当许多模块正在运行时,有时会引发错误,使所有操作停止。该错误表明.lock文件已经存在。这似乎是违反直觉的-如果.lock文件已经存在,则模块应等待直到不存在。使用上述选项,模块应重试访问该锁1000次,但这似乎不起作用。

关于如何防止这种情况的任何想法?

以下是引发的示例错误:

Error: EEXIST: file already exists, open './Config/presetString.txt.lock'

2 个答案:

答案 0 :(得分:2)

documentation

  

同步方法返回值/抛出错误,其他方法则不。标准节点文件。

您需要检查现有锁并使用回调

 // opts is optional, and defaults to {}
lockFile.lock('some-file.lock', opts, function (er) {
   // if the er happens, then it failed to acquire a lock.
   // if there was not an error, then the file was created,
   // and won't be deleted until we unlock it.

  //read file

   var preset = fs.readFileSync("./Config/presetString.txt", 'utf8');

   // do my stuff, free of interruptions
   // then, some time later, do:
lockFile.unlock('some-file.lock', function (er) {
   // er means that an error happened, and is probably bad.
   })
})

答案 1 :(得分:0)

我发现fs-ext的工作状况非常完美,并且真的可以成群!

npm install fs-ext

JavaScript:

过程1

const fs = require("fs");
const {flockSync} = require('fs-ext');
const fd = fs.openSync('file.txt', 'w');
flockSync(fd, 'ex');

过程2

const fs = require("fs");
const {flockSync} = require('fs-ext');
const fd = fs.openSync('file.txt', 'r');
flockSync(fd, 'sh'); // PENDING until Process 1 release exclusive lock!