繁体   English   中英

Node.js:如何从其回调中再次调用函数

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

我想在服务器中创建目录。 但是要检查是否已经存在同名。 如果不存在目录,则使用提供的名称创建目录。 否则,在提供的名称后附加一个随机字符串,然后重新检查是否存在具有新名称的字符串。

到目前为止,我已经能够编写一个执行初始检查的函数,并创建一个不存在的函数。 但是不知道是否存在目录再次运行检查。

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
    });
}

并调用该函数

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");
    }
});

因此,简而言之,我想在服务器中创建具有唯一名称的目录..请帮助我解决此问题..谢谢

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

或者,您可以将功能合并为一个:

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
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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