2012-12-19 3 views
2

node.js와 nano를 사용하여 CouchDB에 첨부 파일을 대량 업로드하려고합니다. 먼저 보행 모듈은 업로드 폴더의 모든 파일을 찾아서 배열을 생성하는 데 사용됩니다. 다음으로, 배열의 각 파일은 pipe와 nano 모듈을 통해 CouchDB에 삽입된다. 그러나 최종 결과는 하나의 첨부 파일 만 업로드되었음을 나타냅니다.node.js nano 모듈을 사용하여 couchDB에 첨부 파일 대량 업로드

var nano = require('nano')('http://localhost:5984') 
var alice = nano.use('alice'); 
var fs = require('fs'); 
var walk = require('walk'); 
var files = []; 

// Walker options 
var walker = walk.walk('./uploads', { 
    followLinks: false 
}); 

// find all files and add to array 
walker.on('file', function (root, stat, next) { 
    files.push(root + '/' + stat.name); 
    next(); 
}); 

walker.on('end', function() { 
    // files array ["./uploads/2.jpg","./uploads/3.jpg","./uploads/1.jpg"] 
    files.forEach(function (file) { 
     //extract file name 
     fname = file.split("/")[2] 

     alice.get('rabbit', {revs_info: true}, function (err, body) { 

       fs.createReadStream(file).pipe(

        alice.attachment.insert('rabbit', fname, null, 'image/jpeg', { 
         rev: body._rev 
        }, function (err, body) { 
         if (!err) console.log(body); 
        }) 


       ) 


     }); 



    }); 


}); 

답변

1

비동기 API를 동기화하는 가정하에 비동기 API를 혼합하기 때문입니다.

첫 번째 요청 후 충돌이 발생하여 토끼 문서가 변경되었습니다.

NANO_ENV=testing node yourapp.js을 사용하여 이것을 확인할 수 있습니까? 아래의 작업이다 -이 그것은 내가 흐름 제어에 대한 자습서를 발견 problem-를 가리키는위한 case.Thank 당신이고 그것을 따라 코드를 수정 문제

+0

경우

내가 비동기를 사용하는 것이 좋습니다 예 : – user1276919

0
var nano = require('nano')('http://localhost:5984') 
var alice = nano.use('alice'); 
var fs = require('fs'); 
var walk = require('walk'); 
var files = []; 

// Walker options 
var walker = walk.walk('./uploads', { 
    followLinks: false 
}); 

walker.on('file', function (root, stat, next) { 
    files.push(root + '/' + stat.name); 
    next(); 
}); 

walker.on('end', function() { 
    series(files.shift()); 

}); 



function async(arg, callback) { 
    setTimeout(function() {callback(arg); }, 100); 
} 


function final() {console.log('Done');} 


function series(item) { 
    if (item) { 
     async(item, function (result) { 
      fname = item.split("/")[2] 

      alice.get('rabbit', { revs_info: true }, function (err, body) { 
       if (!err) { 

        fs.createReadStream(item).pipe(
        alice.attachment.insert('rabbit', fname, null, 'image/jpeg', { 
         rev: body._rev 
        }, function (err, body) { 
         if (!err) console.log(body); 
        }) 


        ) 

       } 
      }); 

      return series(files.shift()); 
     }); 
    } 

    else { 
     return final(); 
    } 
} 
+0

"async"에 대한 정의로 100ms 지연되는 이유는 무엇입니까? 왜 0ms가 아니라면 현재 실행 스택이 완료 되 자마자 async가 시작되어야 함을 나타냅니다. 그냥 노드 또는 js에 대한 뉘앙스가 빠지지 않았는지 확인하고 싶습니다. –

관련 문제