FCF 2.0 development in progress...
> > > >
[News] [Packages API] [Downloads] [Donate to the project] [Contacts]

fcf.NLock.lockFile() function

[SERVER ONLY] fcf.NLock.lockFile(string a_filePath, function a_cb)
[SERVER ONLY] fcf.NLock.lockFile(number a_fileHandle, function a_cb)

Package: fcf-framework-lock

File: fcf-framework-lock:index.js

Available from version: 1.0.0

Performs file locking using the flock or LockFileEx function

Arguments

string a_filePath
- The path to the file.

number a_fileHandle
- The open file handle returned by the FS.open() functions

function a_cb
- The function of processing the result of the function execution

Function signature: a_cb(Error|undefined a_error, number a_lock)

  • Error|undefined a_error - If the function executed with an error, then the argument contains an error object

  • number a_lock - Contains a lock handle to be passed to the unlockFile function to unlock the file.

Example: Locking when using a file path

const libLock = require("fcf-framework-lock"); function action(a_name) { console.log(`Action ${a_name}: Start locking file...`); libLock.lockFile("index.js", (a_error, a_lock)=>{ if (a_error){ console.log("Error lock on file"); process.exit(1); } console.log(`Action ${a_name}: We do some action`); setTimeout(()=>{ console.log(`Action ${a_name}: Removing a lock from a file`); libLock.unlockFile(a_lock, (a_error)=>{ if (a_error){ console.log("Error unlock on file"); process.exit(1); } }); }, 1000); }) } action("1"); action("2");

Output:

Action 1: Start locking file... Action 2: Start locking file... Action 1: We do some action Action 1: Removing a lock from a file Action 2: We do some action Action 2: Removing a lock from a file

Example: Locking when using a file handle

let libFS = require("fs"); let libUtil = require("util"); let libLock = require("fcf-framework-lock"); async function action(a_name) { let file, lock; await new Promise((a_res)=>{a_res();}) .then(async ()=>{ console.log(`Action ${a_name}: Start locking file...`); file = await libUtil.promisify(libFS.open)("index.js", "r"); lock = await libUtil.promisify(libLock.lockFile)(file); console.log(`Action ${a_name}: We do some action`); await new Promise((a_res, a_rej)=>{ setTimeout(()=>{ a_res(); }, 1000); }); }) .finally(async ()=>{ if (lock) { console.log(`Action ${a_name}: Removing a lock from a file`); await libUtil.promisify(libLock.unlockFile)(lock); } }) .finally(async ()=>{ if (file) { await libUtil.promisify(libFS.close)(file); } }); } action("1"); action("2");

Output:

Action 1: Start locking file... Action 2: Start locking file... Action 1: We do some action Action 1: Removing a lock from a file Action 2: We do some action Action 2: Removing a lock from a file