Languages
[Edit]
EN

Node.js - delete files

0 points
Created by:
Dirask Admin - MR
1340

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');

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