example.js
function getCurrentFileSize(counter, timeout, cb) {
  var fd = fs.openSync(__filename, 'r');

  console.log("Trying to aquire lock for the %s time", counter);

  fs.flock(fd, 'exnb', function(err) {
    if (err) {
      return console.log("Couldn't lock file", counter);
    }

    console.log('Aquired lock', counter);

    // unlock after `timeout`
    setTimeout(function() {
      fs.flock(fd, 'un', function(err) {
        if (err) {
          return console.log("Couldn't unlock file", counter);
        }

        if (cb) { cb(); }
      });
    }, timeout);
  });
}
function getCurrentFileSize(counter, timeout, cb) {
  var fd = fs.openSync(__filename, 'r');

  console.log("Trying to aquire lock for the %s time", counter);

  fs.flock(fd, 'exnb', function(err) {
    if (err) {
      return console.log("Couldn't lock file", counter);
    }

    console.log('Aquired lock', counter);

    // unlock after `timeout`
    setTimeout(function() {
      fs.flock(fd, 'un', function(err) {
        if (err) {
          return console.log("Couldn't unlock file", counter);
        }

        if (cb) { cb(); }
      });
    }, timeout);
  });
}
function getCurrentFileSize ( counter , timeout , cb ) { var fd = fs . openSync ( __filename , 'r' ) ; console . log ( "Trying to aquire lock for the %s time" , counter ) ; fs . flock ( fd , 'exnb' , function ( err ) { if ( err ) { return console . log ( "Couldn't lock file" , counter ) ; } console . log ( 'Aquired lock' , counter ) ; // unlock after `timeout` setTimeout ( function ( ) { fs . flock ( fd , 'un' , function ( err ) { if ( err ) { return console . log ( "Couldn't unlock file" , counter ) ; } if ( cb ) { cb ( ) ; } } ) ; } , timeout ) ; } ) ; }
Function that locks the current file
for `timeout` miliseconds

The `counter` represents an index of how many
times the function has been called so far
(it acts as an id)

The callback `cb` is optional
Function that locks the current file for timeout miliseconds