0

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

2
  • Browser? NodeJS? Commented Nov 27, 2017 at 11:40
  • google chrome, yes NodeJs project with angular Commented Nov 27, 2017 at 11:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

hello @Fenton there is [mask: number] what is this mask for ?
That's for the directory permissions: filepermissions.com/directory-permission/0744

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.