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

index.ts
import fs from 'fs-extra';

async function createDirectories(dirname: string): Promise<void> {
  try {
    await fs.mkdirp(dirname);
    console.log(`Directory "${dirname}" has been created successfully.`);
  } catch (error) {
    console.error(`Failed to create directory "${dirname}".`);
  }
}

createDirectories('path/to/new/directory');
341 chars
13 lines

Here, we are importing the fs-extra library and using the mkdirp function to create a directory. mkdirp is an asynchronous function that recursively creates the directories specified in the path. To call the mkdirp function, we pass the path of the desired directory as an argument. We then use console.log and console.error to log our success or failure message respectively, depending on the outcome of the mkdirp function.

Using the async and await keywords ensure that our function returns a promise, which we can then wrap in a try-catch block to handle any errors that may occur during directory creation.

gistlibby LogSnag