0

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?

Gudari
  • 287
  • 1
  • 16
Jeon
  • 4,000
  • 4
  • 28
  • 73

2 Answers2

2

I think you are asking the wrong question. If you check at time T, then write at time T + 1ms, what would guarantee that the file is still writeable?

If the file is not writeable for whatever reason, the write will fail, period. Nothing to do. Your code is fine, but you can probably also do without the fs.writeFileSync(), which will just erase whatever else was in the file before.

You can also write to a randomly-generated file path to make reasonably sure that two processes are not writing to the same file at the same time, but again, that will not prevent all possible write errors, so what you really, really want is rather some good error handling.

In order to handle errors properly you have to provide a callback!

Something along the lines of:

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

Beware, this is asynchronous code, so you need to handle that as well!

frsechet
  • 770
  • 5
  • 14
  • I know it's not guaranteed at T and T+1, so I called it a sort of hack. And `console.log(err)` is just an example for try-catch. Point is whether there is less ugly solution than writing zero string for resource test. – Jeon Jan 01 '19 at 14:23
1

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);
    }
});
Kiruse
  • 88
  • 1
  • 5