随手写了一个文件搜索,发现性能超过Windows自带的
发布于 8 年前 作者 dou4cc 5334 次浏览 来自 分享

find.js如下,直接运行:参数是用来匹配文件(夹)名的正则表达式,I开头则区分大小写,搜索范围即工作目录;Windows系统须以管理员身份运行,否则find.js不能区分文件夹和它的链接,Linux不清楚;搜索结果直接log在console里。

"use strict";

const fs = require("fs");
const [$ = process.exit()] = [process.argv[2]];
const reg =
	$.startsWith("I")
	? RegExp($.slice(1), "u")
	: RegExp($, "iu");

const visit = path => {
	const list = [];
	for(let name of fs.readdirSync(path)){
		try{
			const pathname = path + name;
			if(fs.statSync(pathname).isDirectory()){
				if(reg.test(name)){
					log(pathname + "/");
					list.push(...visit(pathname + "/"));
				}else{
					list.push(pathname + "/");
				}
			}else if(reg.test(name)) log(pathname);
		}catch(error){}
	}
	return list.length === 1 ? visit(list[0]) : list;
};

const search = function*(path){
	try{
		const head = {};
		let p = head;
		for(let i of visit(path)){
			p = p.next = {value: search(i)};
		};
		while(head.next){
			p = head;
			while(p.next){
				yield;
				if(p.next.value.next().done){
					p.next = p.next.next;
				}else{
					p = p.next;
				}
			}
		}
		yield;
	}catch(error){}
};

let t2;
const log = msg => {
	if(t2){
		t2 = Date.now();
	}else{
		t2 = Date.now();
		console.log("找出第一条结果的用时:" + (t2 - t1) + "ms");
	}
	console.log(msg);
};

const t1 = Date.now();
for(let i of search("./"));

if(t2) console.log("从开始搜索到找出最后一条结果的用时:" + (t2 - t1) + "ms");
6 回复

能超过 everything 就算你真牛X~

刚刚改进了代码。

@mmy 我的find.js的全盘遍历用时不比Windows短,但因为使用了改进的宽搜,不会被某个特大文件夹卡住,通常要找的文件很快被找到。另,find.js是无索引、不预加载的,和everything不是一个量级啊。

@dou4cc 说破大天去,nodejs 底层还是用的Windows的API(好像是 FindFile/FindNexFile),系统自带的搜索同样是用这个,所以根本就不可能更快。。。 如果你感觉更快,那是因为文件系统的缓存机制,无论用什么语言编,只要用到FindFile/FindNexFile,第一次会稍慢,后面再遍历就会相当快了。。

@myy 你把我之前的回复再读一遍,再把find.js运行一遍!

更新了代码

回到顶部