首页 > js在目标文件夹检索想要命名的文件是否存在,如果存在则重新命名?

js在目标文件夹检索想要命名的文件是否存在,如果存在则重新命名?

想要创建一个文件,名字已经备好,在目标文件夹检索改名字是不是已经被占用,如果占用则给文件重新命名。

/**
 * Created by Administrator on 2016/8/10.
 */

function File(){
    var _checkFile = require('check-file-exists');
    var _createFile = require('create-file');
    return {
        check: _checkFile,
        create: _createFile
    }
}
var file = new File();
var aimdir = '../../../projectNew/';
var fileName = 'a_0.txt';
var exists = true;
var fileEnd = /\d/g.exec(fileName);


while(exists){
    console.log('exists是 '+ exists +'\n fileEnd是 '+ fileEnd);
    file.check(aimdir+fileName, function(err,exist){
        if(exist == true){
            console.log('exists是 '+ exists +'\n exist是 '+ exist);
            fileName = fileName.replace(/\d/g,+fileEnd+1);
        }else{
            exists = false;
            file.create(aimdir+fileName,'',function(err){});
        }
    });
}

运行的时候出现死循环,求解。


原因是:RegExp.exec 返回一个数组

其实你这样替换检查很蹩脚,不如这样:

var fs = require('fs');
var aimdir = '../../../projectNew/';
var index = 0;


while (True) {
    if (!fs.lstatSync(var path = `${aimdir}a_${index++}.txt`)).isFile()) {
        // create file with `path`
        break;
    }
}

这点东西还用异步简直是自我伤害

小脚本其实可以摒弃异步,用微弱的性能下降换取极大的开发效率提升。

【热门文章】
【热门文章】