gpt4 book ai didi

javascript - 递归读取目录中的所有文件 - FileSystem API

转载 作者:行者123 更新时间:2023-11-28 08:00:15 25 4
gpt4 key购买 nike

我对如何递归读取文件列表感到困惑。假设我的文件系统 api 根目录中有 3 个文本文件

  • text1.txt
  • text2.txt
  • text3.txt

我的目标是逐个读取每个文本文件,然后将每个文件中的所有条目连接成一个字符串,但我目前迷失了如何在 Javascript FileSystem API 中执行此操作。

window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);
function onInitFs(fs) {
var dirReader = fs.root.createReader();
var entries = [];

// Call the reader.readEntries() until no more results are returned.
var readEntries = function() {
dirReader.readEntries (function(results) {
if (!results.length) {
readAllFiles(results);
} else {
entries = entries.concat(toArray(results));
readEntries();
}
}, errorHandler);
};
readEntries(); // Start reading dirs.
}

function readAllFiles(entries){
//Loop thru all the files and read each entries
}

我已经了解了如何读取一个文本文件,但我不知道如何实现所有文件的读取并连接值。它们都实现了回调函数,所以我对如何处理它感到困惑。请问有什么积分吗?

实际上我所有的作品都基于这个http://www.html5rocks.com/en/tutorials/file/filesystem

更新2根据@Johan我实际上更改了代码以利用回调

 window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);
function onInitFs(fs) {
var dirReader = fs.root.createReader();
var entries = [];

// Call the reader.readEntries() until no more results are returned.
var readEntries = function() {
dirReader.readEntries (function(results) {
if (!results.length) {
readAllFiles(results, concatMessages);
} else {
entries = entries.concat(toArray(results));
readEntries();
}
}, errorHandler);
};
readEntries(); // Start reading dirs.
}


var concatMessage = '';

function concatMessages(message){
concatMessage += message;
}

function readAllFiles(logs, callBack) {
logs.forEach(function(entry, iCtr) {
var message;

entry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
//message += this.result;
if(callBack)
callBack('==================' + iCtr + '==========================');
callBack(this.result);
};
reader.readAsText(file); // Read the file as plaintext.
}, function(err) {
console.log(err);
});

});

}

我唯一的问题是,回调函数不是连续的。它首先读取text2.txt,然后读取text3.txt,然后读取text1.txt,因此最终结果不是连续的,这不是我想要做的。还有更多提示吗?

最佳答案

强烈建议您考虑使用类似 caolan 的 async 的东西库来完成此任务。

你可以这样做:

async.each(openFiles, function(file, callback) {

// Perform operation on file here.
console.log('Processing file ' + file);
callback();
}, function(err) {
// if any of the file processing produced an error, err would equal that error
if (err) {
// One of the iterations produced an error.
// All processing will now stop.
console.log('A file failed to process');
} else {
// do your concatenation here
}
});

关于javascript - 递归读取目录中的所有文件 - FileSystem API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25527959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com