1
我想用search-index来索引大约20个目录,每个目录中有大约10,000个文件。我预计该操作需要花费数小时,所有数据都无法存储到内存中,而且我希望将这些添加内容分批添加到一次显示的十个或二十个数据中。等待节点异步操作
基本的代码看起来是这样,创建一个搜索索引并执行一个回调函数,当它准备有实例“SI”的位置:
searchIndex(siOptions, (sierr, si) => {
// here I list the files and want to do batch adds:
while (true) {
var batch = getBatch();
if (!batch) break;
si.add(batch, options, (err) => {
console.timeEnd('batch');
});
}
});
所以我的基本思想是通过目录循环,写的是,我在处理该目录,列出文件,并处理的文件批量的说,20在一个时间:
_.each(subDirs, dir => {
// list files
// pull 20 files at a time
// do add above
});
所以我知道我能做,但宕它看起来丑陋。能够使这个同步运行将是理想的,但是我可以使用一些实用程序库吗?我的想法是创建一个函数来处理目录,并经历一次一个,并增加了回调的柜台里面,并调用本身...
var dirIndex = 0;
var doDir = function(cbDir) {
if (dirIndex >= dirs.length) cbDir(); // done
var batches = _.chunk(fs.readdirSync(dirs[dirIndex]), 20);
var batchIndex = 0;
var doBatch = function(cbBatch) {
if (batchIndex >= batches.length) {
cbBatch();
return;
}
console.time('batch');
si.add(batch[batchIndex++], options, (err) => {
doBatch(cbBatch); // process next batch, have it call our callback
});
};
doBatch(() => doDir(cbDir)); // final callback will do next dir
}
好像我可能会开放自己变化范围等问题。有没有更好的办法?我假设所有搜索索引都不会有问题,因为在所有操作完成之前函数searchIndex(siOptions, (sierr, si) => {
已经返回...
首先想到的两件事是['async'](http://caolan.github.io/async/)或Promises。 'async'会修改你的代码的很大一部分,但保持它的漂亮,干净和异步。目前,我们首选Promise,我已经看到他们习惯于“同步”代码,所以可能会更合适。 – DrakaSAN