Languages
[Edit]
EN

Node.js - delete files

0 points
Created by:
Zayaan-Rasmussen
543

In this article, we would like to show you how to delete files in Node.js.

Below we will present 3 methods to delete files in node.js:

  • synchronously,
  • asynchronously with callback,
  • asynchronously with async/await.

Synchronously

const fs = require('fs');

try {
    fs.unlinkSync('./fileToDelete.txt');
    console.log('successfully deleted fileToDelete.txt');
} catch (error) {
    console.log(error);
}

Asynchronously with callback

const fs = require('fs');

fs.unlink('./fileToDelete.txt', (error) => {
    if (error) {
        console.error(error.message);
    } else {
        console.log('successfully deleted');
    }
});

Asynchronously with async/await

const fs = require('fs/promises');

const deleteFile = async (path) => {
    try {
        await fs.unlink(path);
        console.log('successfully deleted');
    } catch (error) {
        console.error(error.message);
    }
};

deleteFile('./fileToDelete.txt');

Alternative titles

  1. Node.js - how to delete files
  2. Node.js - remove files
  3. Node.js - remove file (delete file)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - file system module

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join