Skip to content

Commit 62d7876

Browse files
committed
feat(utils): add function "createTmpDir" and "removeDir"
1 parent 33183fd commit 62d7876

File tree

1 file changed

+50
-0
lines changed
  • packages/mongodb-memory-server-core/src/util

1 file changed

+50
-0
lines changed

packages/mongodb-memory-server-core/src/util/utils.ts

+50
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
BinaryNotFoundError,
99
InsufficientPermissionsError,
1010
} from './errors';
11+
import { tmpdir } from 'os';
12+
import * as path from 'path';
1113

1214
const log = debug('MongoMS:utils');
1315

@@ -306,3 +308,51 @@ export async function checkBinaryPermissions(path: string): Promise<void> {
306308
export async function mkdir(path: string): Promise<void> {
307309
await fspromises.mkdir(path, { recursive: true });
308310
}
311+
312+
/**
313+
* Create a Temporary directory with prefix, and optionally at "atPath"
314+
* @param prefix The prefix to use to create the tmpdir
315+
* @param atPath Optionally set a custom path other than "os.tmpdir"
316+
* @returns The created Path
317+
*/
318+
export async function createTmpDir(prefix: string, atPath?: string): Promise<string> {
319+
const tmpPath = atPath ?? tmpdir();
320+
321+
return fspromises.mkdtemp(path.join(tmpPath, prefix));
322+
}
323+
324+
// outsourced instead of () or without, because prettier cant decide which it wants
325+
type tfsPromises = typeof fspromises;
326+
327+
// workaround for already using @types/node 14 (instead of 12)
328+
interface RmDir {
329+
rmdir: tfsPromises['rmdir'];
330+
}
331+
332+
/**
333+
* Removes the given "path", if it is a directory, and does not throw a error if not existing
334+
* @param dirPath The Directory Path to delete
335+
* @returns "true" if deleted, otherwise "false"
336+
*/
337+
export async function removeDir(dirPath: string): Promise<void> {
338+
const stat = await statPath(dirPath);
339+
340+
if (isNullOrUndefined(stat)) {
341+
return;
342+
}
343+
344+
if (!stat.isDirectory()) {
345+
throw new Error(`Given Path is not a directory! (Path: "${dirPath}")`);
346+
}
347+
348+
if ('rm' in fspromises) {
349+
// only since NodeJS 14
350+
await fspromises.rm(dirPath, { force: true, recursive: true });
351+
} else {
352+
// before NodeJS 14
353+
// needs the bridge via the interface, because we are using @types/node 14, where this if evaluates to a always "true" in typescript's eyes
354+
await (fspromises as RmDir).rmdir(dirPath, {
355+
recursive: true,
356+
});
357+
}
358+
}

0 commit comments

Comments
 (0)