简体   繁体   中英

Node.js: How to call a function again from its callback

I want to create a directory in server. But want to check if one exists already with the same name. If no directory exists then create one with the name provided. Otherwise append a random string to the provided name and recheck if one exists with the new name.

So far, I'm able to write a function that perform the initial check and create one if it doesn't exists. But no idea to run the check again if a directory exists.

var outputDir = __dirname + '/outputfiles/' + values.boxname;

function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') {
        cb = mask;
        mask = 484;
    }
    fs.mkdir(path, mask, function(err) {
        if (err) {
            cb(err);
        } else cb(null); // successfully created folder
    });
}

and calling the function

ensureExists(outputDir, 484, function(err) {
    if (err) {
        if (err.code == 'EEXIST') {
            var outputDir = outputDir + '-' + Date.now();
            // NEED Help here to call this function again to run the check again
            return console.log("A Folder with same name already exists");
        } else {
            console.err(err);
        };
    } else {
        console.log("Folder created");
    }
});

So, In short I want to create directories in server with unique names..please help me to fix this problem..thanks

function callback(err) {
    if (err) {
        if (err.code == 'EEXIST') {
            var outputDir = outputDir + '-' + Date.now();
            // NEED Help here to call this function again to run the check again
            ensureExists(outputDir, 484, callback); // Call again
            return console.log("A Folder with same name already exists");
        } else {
            console.err(err);
        };
    } else {
        console.log("Folder created");
    }
}
ensureExists(outputDir, 484, callback); // Call first

Or you could merge the functionality into one:

function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') {
        cb = mask;
        mask = 484;
    }
    fs.mkdir(path, mask, function(err) {
        if (err) {
            if (err.code == 'EEXIST') {
                var newpath = path + '-' + Date.now();
                ensureExists(newpath, mask, cb); // rerun with new path
                console.log("A Folder with same name already exists");
            } else {
                console.err(err);
            };
        } else cb(path); // successfully created folder
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM