노드를 사용하여 하위 디렉토리를 포함하는 디렉토리에 포함 된 고유 한 파일 이름 목록을 가져오고 각 콜백 결과를 결합하는 데 문제가있었습니다. 난 중복에 대한 작업을 피하고 싶습니다. 어떤 경우에만 fs.stat
콜백에서 파일 이름을 로그하면 어떻게됩니까?Node.js 누적 기가있는 async 디렉토리 트래버스
var distinct = {};
function getNames(root) {
fs.readdir(root, function(err, list) {
list.forEach(function(file) {
file = root + '/' + file;
fs.stat(file, function(err, stat) {
if (!err && stat.isDirectory()) {
getNames(file);
} else {
distinct[path.basename(file)] = true;
}
});
});
});
}
// perform various operations on unique filename list
console.log(Object.keys(distinct));
물론 이것은 console.log()
함수를 너무 일찍 호출하여 원하지 않는 결과를 가져옵니다. 어떻게하면 작업 할 파일 이름 집합을 얻을 수 있습니까? 비동기 메서드를 사용하여이 작업을 수행하는 좋은 방법이 있습니까? 예 : readdirSync
및 statSync
을 사용할 필요가 없나요?
팁 하나를'root + '/'+ file' 대신'path.join (root, file)'을 사용하십시오. – naomik