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

index.ts
import { ensureFile } from "fs-extra";

async function createFile(filePath: string): Promise<void> {
  try {
    await ensureFile(filePath);
    console.log(`File created successfully at ${filePath}`);
  } catch (err) {
    console.error(`Error occurred while creating file: ${err}`);
  }
}

const FILE_PATH = "./test.txt";
createFile(FILE_PATH);
347 chars
14 lines

Here we have imported the ensureFile function from the fs-extra library in TypeScript. We have defined an async function createFile which takes a filePath argument and returns a Promise of type void.

Inside the createFile function, we use the ensureFile function to ensure that the file specified in the filePath argument exists. This function creates an empty file if it does not exist, and does nothing if it already exists.

We then log to the console a message indicating whether the file was successfully created or not.

At the end, we call the createFile function with a file path that we have defined.

Note that since ensureFile is an asynchronous function, we need to await its result using the await keyword. Additionally, we have wrapped the call to ensureFile in a try-catch block to handle any errors that may occur during file creation.

gistlibby LogSnag