Search code examples
node.jsfileexcel4node

How to check file is writable (resource is not busy nor locked)


excel4node's write to file function catches error and does not propagate to a caller. Therefore, my app cannot determine whether write to file is successful or not.

My current workaround is like below:

let fs = require('fs')
try {
  let filePath = 'blahblah'
  fs.writeFileSync(filePath, '') // Try-catch is for this statement
  excel4nodeWorkbook.write(filePath)
} catch (e) {
  console.log('File save is not successful')
}

It works, but I think it's a sort of hack and that it's not a semantically correct way. I also testedfs.access and fs.accessSync, but they only check permission, not the state (busy/lock) of resource.

Is there any suggestion for this to look and behave nicer without modifying excel4node source code?


Solution

  • You already marked a line in the library's source code. If you look a few lines above, you can see it uses the handler argument to pass any errors to. In fact, peeking at the documentation comment above the function, it says:

    If callback is given, callback called with (err, fs.Stats) passed

    Hence you can simply pass a function as your second argument and check for err like you've probably already seen elsewhere in the node environment:

    excel4nodeWorkbook.write(filepath, (err) => {
        if (err) {
            console.error(err);
        }
    });