how to use the unlink function from the fs-extra library in typescript

To use the unlink function from the fs-extra library in TypeScript, first, you need to install the library via npm:

index.ts
npm install fs-extra
21 chars
2 lines

Then, you can import the function and call it like this:

index.ts
import { unlink } from 'fs-extra';

async function deleteFile(filePath: string) {
  try {
    await unlink(filePath);
    console.log('File deleted successfully');
  } catch (err) {
    console.error(err);
  }
}
212 chars
11 lines

In this example, unlink is an asynchronous function that takes a filePath argument, which is the path to the file you want to delete. The function returns a promise that resolves to undefined, or rejects with an error if the file could not be deleted.

To handle the promise, we use await before calling unlink, allowing us to write the function in a synchronous style.

By wrapping the function body in a try-catch block, we can handle any errors that might occur during the deletion process.

Finally, we print a success message to the console if the file was deleted successfully.

gistlibby LogSnag