【问题标题】:How to effectively lock a text file while using it in NodeJS?在 NodeJS 中使用文本文件时如何有效地锁定它?
【发布时间】:2019-06-16 14:47:49
【问题描述】:

我有几个独立的脚本从同一个文本文件中读取和写入。我试图在模块读取/写入文本文件时锁定文本文件。目前我正在使用 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'

【问题讨论】:

    标签: javascript node.js lockfile


    【解决方案1】:

    来自documentation

    同步方法返回值/抛出错误,其他方法不返回。标准节点 fs 的东西。

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

     // 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.
       })
    })
    

    【讨论】:

      【解决方案2】:

      我发现fs-ext 工作完美,并且真的执行了flock!

      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!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        • 2010-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        • 2022-01-25
        相关资源
        最近更新 更多