Home > Enterprise >  Node.js fs.unlink() executes properly but hangs. How do we end it gracefully
Node.js fs.unlink() executes properly but hangs. How do we end it gracefully

Time:04-15

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
  }
}

CodePudding user response:

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))
  • Related