Scan.js 1.38 KB
var fs = require('fs');
var path = require('path');

module.exports=function(url){
	var tokens=[],files=[],dir="";
	url.split(/\/\{|\}/).forEach(function(item,index) {
		if(item){
			tokens.push({
				value:item,
				expr:index%2?true:false
			});
		}
	});

	function scanFolder(src) {
	    var stats,fileList = [],
	        folderList = [],
	        walk = function (src, fileList, folderList) {
	        	
	            files = fs.readdirSync(src);
	            files.forEach(function (item) {
	                var tmpPath = path.join(src, item);

	                stats = fs.statSync(tmpPath);
	                
	                if (stats.isDirectory()) {
	                    walk(tmpPath, fileList, folderList);
	                    folderList.push(tmpPath);
	                } else {
	                    fileList.push(tmpPath);
	                }
	            });
	        };
	    
	    walk(src, fileList, folderList);
	    
	    return {
	        'files': fileList,
	        'folders': folderList
	    }
	}

	if(fs.statSync(tokens[0].value).isFile()){
		return [path.normalize(tokens[0].value)];
	}
	
	url=url.replace(/^\W+/g,'').replace(/\//g,'\\\\').replace(/\{/g,'(').replace(/\}/g,'?)');
	var regex = new RegExp("^"+url+"$");
	var obj=scanFolder(tokens[0].value),result=[];
	if(path.extname(url)){
		result=obj.files.filter(function(item){
			return regex.test(item);
		});
	}
	return result;

}