Remove files with File System

2

I'm trying to remove two files from my server with the following code:

const fs      = require('fs');
const express = require('express');
const app     = express();

app.delete('/delete', function(req, res){
   fs.unlink('path/doc_1', function(){
       fs.unlink('path/doc_2', function(){
           res.end();
       })
   })
})

But the following error is thrown:

UnhandledPromiseRejectionWarning: Error: EBUSY: resource busy or locked, unlink

Has anyone ever been through this?

    
asked by anonymous 22.08.2018 / 14:15

1 answer

2

Your error says that the file is in use. The suggestion I give you is to make the following change so that, in case of any problem, make it clearer to identify it. With the change the files will be deleted in parallel too:

const fs      = require('fs');
const express = require('express');
const app     = express();

const { promisify } = require('util');
const unlink = promisify(fs.unlink);

app.delete('/delete', async (req, res) => {
  try {
    await Promise.all([unlink('path/doc_1'), unlink('path/doc_2')]);
    res.end();
  } catch(e) {
    console.error(e);
    res.status(500).send('Ocorreu um erro interno.');
  }
});
    
22.08.2018 / 14:51