node.js(javascript)

时间:2019-03-15 08:27:10

标签: javascript node.js mutex

我想知道javascript中是否存在系统范围的互斥锁(不是通常的互斥锁?)?

我有2个或更多正在运行的node.js cmd实例。 这些将读取和写入相同的文件,在这里,我不希望他们在同一时间这样做。

代码如下:

//Enter Systemwide Mutex here
var textarray = fs.readFileSync("C:/file1.txt").toString('utf-8'); //Read the file
fs.promises.writeFile("C:/file1.txt", "hello"); //Write to file
//Exit Systemwide Mutex here

我尝试使用文件锁定方法(https://www.npmjs.com/package/proper-lockfile) 我已经安装了:“ npm我proper-lockfile” 但是我收到一个错误: TypeError:lockfile.lock不是函数

const lockfile = require('C:/myproject/temp/lockfile.txt');

lockfile.lock('C:/myproject/temp/lockfile.txt')
    .then((release) => {
        // Do something while the file is locked

        var textarray = fs.readFileSync("C:/myproject/file1.txt").toString('utf-8'); //Read the file            
        fs.promises.writeFile("C:/myproject/file1.txt", "hello now"); //Write to file
        

        // Call the provided release function when you're done,
        // which will also return a promise
        return release();
    });

2 个答案:

答案 0 :(得分:0)

这是一个有效的代码:

'use strict';
const fs = require('fs');
const lockfile = require('proper-lockfile');

lockfile.lock('C:/myproject/temp/lockfile.txt')
    .then(() => {

        // Do something while the file is locked
        var textarray = fs.readFileSync("C:/myproject/file1.txt").toString('utf-8'); //Read the file
        fs.promises.writeFile("C:/myproject/file1.txt", "hello now"); //Write to file

        // Later..
        return lockfile.unlock('C:/myproject/temp/lockfile.txt');
    });

答案 1 :(得分:-1)

您可以使用诺言

<fragment
    android:id="@+id/exploreFragment"
    android:name="com.decathlon.allforsport.home.explore.ExploreFragment"
    tools:layout="@layout/fragment_explore" />
<fragment
    android:id="@+id/eventsFragment"
    android:name="com.decathlon.allforsport.home.events.EventsFragment"
    tools:layout="@layout/fragment_stories" />
<fragment
    android:id="@+id/storiesFragment"
    android:name="com.decathlon.allforsport.home.stories.StoriesFragment"
    tools:layout="@layout/fragment_stories" />