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

To use mkdtemp function from fs-extra library in TypeScript, we first need to install the fs-extra library and its type definitions.

npm install fs-extra @types/fs-extra --save
44 chars
2 lines

After installing the library and the types, we can import the functions from the library and use it as follows:

index.ts
import { mkdtemp } from "fs-extra";
import { promisify } from "util";

const mkdtempAsync = promisify(mkdtemp);

async function createTempDir(): Promise<string> {
    const prefix = "temp-";
    const tempDir = await mkdtempAsync(prefix);
    return tempDir;
}
261 chars
11 lines

Here, we are using the mkdtemp function from the fs-extra library to create a temporary directory with a given prefix. Since the mkdtemp function returns a callback with an error and the new directory path, we use promisify function from util module to convert it to an async function that returns Promise.

With the createTempDir function, we can call mkdtemp function asynchronously and it will return the generated temporary directory path.

Note: The mkdtemp function creates a unique temporary directory with the prefix passed as argument and replaces six characters of that prefix with random symbols.

gistlibby LogSnag