2015년 9월 22일 화요일

node.js 에서 for문 사용하기 ( Callback 포함 )


출처 : http://www.richardrodger.com/2011/04/21/node-js-how-to-write-a-for-loop-with-callbacks/#.VgIAfdLtlBc




node.js 의 구조적 특성탓에 for문 일반적으로 쓰면 잘안됨.

재귀적인 function 으로 for문 효과를 줄 수 있음.



내 경우에는 다중 이미지 업로드 웹페이지를 만들고 있었음.

 <form method='post' action='/uploads' enctype='multipart/form-data'>  
 <input type='file' name='image' multiple/>  
 <input type='submit' value='전송'/></form>

HTML 은 이런식

그리고 express 를 통해 받았다.

path 에 있는 이미지를 read 해서

다시 내가 원하는 폴더로 파일명을 현재시간(nowsysdate)으로 변경해서

write 하도록 만들었다

결과적으로 잘된다. 굿

function readwrite(j)  
                               {  
                                    if( j < multiNum)  
                                    {  
                                         fs.readFile(req.files.image[j].path, function (err, data)   
                                         {  
                                              var newPath = __dirname + "/uploads/fullsize/" + nowSysDate + j + '.' + splitType;  
                                              console.log('my new Path --> ' + newPath);  
                                              fs.writeFile(newPath, data, function (err)  
                                              {  
                                                   if(err) { log(' fs.writeFile 에러 ---> ' + err ) }  
                                                   else { readwrite(j+1) };   
                                              });       
                                         });  
                                    }  
                               }  
                               readwrite(0);  






댓글 없음:

댓글 쓰기