[英]System wide mutex in node.js(javascript)
我想知道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 iproperty-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(); });
這是一個工作代碼:
'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'); });
你可以用諾言
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");
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.