Delete file automatically after sometime from node server

I am working on a file converter.
First, I get a file from the user and save it to the uploads folder of my node server and after conversion, I saved it to the download folder.
As the file gets converted I delete the uploaded file from the uploads folder by using fs.unlink but after 5000 ms of conversion It deletes the file from the download folder but the problem is when at the same time more than 1 user uploads the file.

It isn’t able to delete the file of the second user from the downloads folder, it shows an error message.
It basically not able to update the name of the second downloaded file for the second user, it still search for the first downloaded file(which is already gets deleted) to delete.

[Error: ENOENT: no such file or directory, unlink 'downloads/1617962744875.yml'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'unlink',
  path: 'downloads/1617962744875.yml'
}

Code:


var path = require('path')

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + path.extname(file.originalname)) //Appending extension
    }
})

app.post("/upload", upload.array("files"), uploadFiles);

const uploadFiles = async (req, res) => {
    const file = await req.files[0];
    postmanCollection = file.path;
    outputFile = `downloads/${file.filename.slice(0, -5)}.yml`
    await convert();
    await fs.unlink(file.path, err => {
        if (err) {
            console.log('error in deleting a file from uploads')
        } else {
            console.log('succesfully deleted from the uploads folder')
        }
    })
    res.json(file);
}

const convert = async () => {
    try {
        let result = // doing my conversion over here
        setTimeout(() => {
            fs.unlink(outputFile, err => {
                if (err) {
                    console.log(err)
                } else {
                    console.log('succesfully deleted from the downloads folder')
                }
            })
        }, 5000)
    } catch (err) {
        console.log(err)
    }
}

Anyone Please help me with this.

You could try to pass outputFile as an argument to convert() and then in the setTimeout you should use that passed variable, instead of using some global-ish variable.

1 Like

Thanks it works
I just create a local variable inside a convert function and it works

  let filePath = outputFile;
        setTimeout(() => {
            fs.unlink(filePath, err => {

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.