Amit Singh Rawat
Amit Singh Rawat

Reputation: 589

directory / file is exist or not using Typescript

There is any way to check if there is any directory/file is exist in location and create using typescript ?

I tried to google but all are in js example I need to know how to do in typescript to that operation

Upvotes: 0

Views: 1714

Answers (1)

Fenton
Fenton

Reputation: 251102

You can do this using the following function, it attempts to create a folder (which errors if it does not exist) and then calls you back.

Functions for folders and files shown:

import * as fs from 'fs';

export function createDirectory(path: string, mask: number | null, cb: (err: NodeJS.ErrnoException | null) => void) {
    if (!mask) {
        mask = 484; //0744
    }

    fs.mkdir(path, mask, (err: NodeJS.ErrnoException) => {
        if (err && err.code !== 'EEXIST') {
            // Error (not folder already exists)
            cb(err);
            return;
        }

        // Folder created, or already exists
        cb(null);
    });
}

export function createFile(path: string, cb: (err: NodeJS.ErrnoException | null) => void) {
    fs.stat(path, (err, stat) => {
        if (err) {
            if (err.code === 'ENOENT') {
                // Create the File
                fs.writeFile(path, '', (err) => {
                    cb(err);
                });
            } else {
                // Error
                cb(err);
            }
        } else {
            // File already exists
            cb(null);
        }
    });
}

It has all the appropriate type annotations that you need to guide you.

Upvotes: 1

Related Questions