-1

I've defined a function to delete a file, to include in teardown for testing.

The delete function works fine, but it hangs forcing a CTRL-C to end the script, and deleteFile('somefile.txt').then(x => console.log(x) shows undefined while it's waiting.

Still a novice JavaScript self-learner. No idea what I'm missing here:

async function deleteFile(file) {
  let result
  try {
    fs.unlink(file, (err) => {
      if (err) throw err;
      result = `Deleted ${file}`
    })
    return result
  } catch (err) {
    return err
  }
}

UPDATE I made the overarching problem I was trying to solve extra complicated. This function isn't necessary. I thought I needed to have a delete function to export into my test. A bit of a convoluted approach since I can simply directly delete the file in the my setup of my test.js.

Also there was an import of an open database handle that was not closing that was causing the script to hang.

Overall this situation was a mess, but I had some assistance in troubleshooting beyond the question posed in this post.

So, this was more an exercise in recognizing how I can make mistakes by being hyper-focused on methodology and losing track of the simple solution.

Part of learning is making wrong turns...from which one can easily recover.

Net learning: Slow down. Keep it simple. Don't hyper-focus.

Ken Ingram
  • 1,538
  • 5
  • 27
  • 52
  • 3
    For starters, `if (err) throw err;` inside an asynchronous callback is not acceptable error handling. At least log the error and then find some better way to handle the asynchronous error. – jfriend00 Apr 14 '22 at 21:24
  • 2
    Showing `undefined` is expected. `fs.unlink()` is non-blocking and asynchronous so it will call its callback long AFTER your function returns and thus `result` will always be `undefined` when it returns. You can't directly return an asynchronous value. For further info on returning an asynchronous result see [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). – jfriend00 Apr 14 '22 at 21:29
  • 2
    Also see [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – jfriend00 Apr 14 '22 at 21:31
  • 1
    And, it really makes non sense to have your own `deleteFile()` function here at all. Just call `fs.unlink()` directly. You're just wrapping it and messing up the error handling (hiding errors) in doing so. Or, use `await fs.promises.unlink(...)` directly which might be simpler to program. – jfriend00 Apr 14 '22 at 21:33
  • After all that feedback, I have no idea why it's "hanging". I'd suggest you put `console.log("in fs.unlink() callback")` right before the `if (err) throw err` to see if it ever gets into that callback. If it does, then your issue is probably not with this code. It's probably with something else. If you have any timers or servers running, those will keep the server from exiting on its own. – jfriend00 Apr 14 '22 at 21:45
  • Cool. Good things to consider. – Ken Ingram Apr 14 '22 at 22:24
  • I overcomplicated this. I can just do fs.unlink in my test. – Ken Ingram Apr 14 '22 at 22:27
  • So, is your program hanging or not? I thought that was the real question here. – jfriend00 Apr 14 '22 at 22:31
  • Yeah the program hangs. The real question was dealing with fs.unlink, which is causing the hang. @i like cola gave a good solution. – Ken Ingram Apr 14 '22 at 22:44
  • It was hanging due to a database connection problem. Had to run debug with some help from someone over my shoulder. – Ken Ingram Apr 14 '22 at 23:17
  • Also, I prefaced my question with the fact that I am a novice and self-teaching this subject. – Ken Ingram Apr 14 '22 at 23:19

1 Answers1

1
const fs = require('fs')

function deleteFile(file) {
    return new Promise((resolve, reject) => {
        fs.unlink(file, (err) => {
            if (err) reject(err);
            resolve(`Deleted ${file}`)
        })
    })
}
deleteFile(some file).then(x => console.log("res", x)).catch(err=>console.log(err.message))
i like Cola
  • 277
  • 6
  • 15
  • While this is a better version of `deleteFile()` (which could also just use the built-in `fs.promises.unlink()`, how does this fix the "hanging" problem that the OP specifically asks about? – jfriend00 Apr 14 '22 at 22:04
  • @jfriend00 I think you're extra focused on "right" when really it's just an exercise. As it turns out, I made this issue more complex than it really is. – Ken Ingram Apr 14 '22 at 22:46
  • 1
    @KenIngram - Well, as a relatively new user, I'm trying to point out that [`fs.promises.unlink()`](https://nodejs.org/api/fs.html#fspromisesunlinkpath) is already built into nodejs so the `deleteFile()` function in this answer is not necessary at all. Yes, I'm pointing out the "right" way to do things. That's what we try to do here. – jfriend00 Apr 15 '22 at 03:00
  • And you're missing my point which is you made that point a number of times such that it has become excessive. Learning involves doing things that fail. I understand the function was unnecessary, but I needed to do it this way to see why. – Ken Ingram Apr 15 '22 at 17:20
  • I already made the note that I overcomplicated my solution, which is a flaw in my method. Thank you for your servive. – Ken Ingram Apr 15 '22 at 17:21