简体   繁体   中英

System wide mutex in node.js(javascript)

I wonder if there is a System wide mutex in javascript( Not an usual mutex with other words )?

What I have is 2 or more instances of a node.js cmd running. Those will read and write to the same file and here I don't want them to do that at the exact same time.

The code looks like this:

 //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 

I have made an attempt using the file lock approach( https://www.npmjs.com/package/proper-lockfile ) I have installed with: "npm i proper-lockfile" But I receive an error: TypeError: lockfile.lock is not a function

 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(); }); 

This is a working code:

 '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'); }); 

You can do using promise

var p_readFile = new Promise(function(resolve, reject){
    fs.readFile("C:/file1.txt", type, (err, d) => {
        err ? reject(err) : resolve(d);
    });
})

p_readFile.then(function(d){
     console.log(d); 
     //Write Your Write file Syntax Here
     fs.promises.writeFile("C:/file1.txt", "hello");
   })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM