2012-08-22 45 views
0

我希望我能得到一些建議,說明爲什麼我的nodejs程序的行爲方式如此。Node.js - 組織代碼和關閉 - SFTP/Inotify

我使用了兩個模塊,node-sftp和node-inotify。我已經設置node-inotify來查看一個目錄,並在寫入內容時調用一個函數,該函數是一個sftp上傳。

現在我遇到的問題是,一次處理一個文件是好的,但是當我一次去掉4個文件時,函數會被調用四次,但只有一個sftp上傳會通過。

我是否需要以特定的方式訂購我的代碼以確保sftp上傳發生x次,這可能與閉包有關嗎?

這是我的代碼基本版本...

  • 「event_handler」當事情發生在「監視」目錄
  • 「check_event」出來,如果這種類型的事件是一個數字被稱爲我們希望,在這種情況下,這是一個「寫」
  • 「ftp_to_server」準備連接細節
  • 「do_ftp」基本上是採用節點SFTP模塊進行SFTP上傳

    event_handler = function(event){ 
        var supplier; 
        check_event(event, supplier, type, ftp_to_server); 
    }; 
    

=================

function check_event(event, handler) 
    { 
     if (event.type === 'xxxxxx') { 
      var file_to_process_name = 'abc'; 
      var file_to_process_dir = 'abc'; 
      var remote_dir = 'abc'; 
      handler(file_to_process_name, file_to_process_dir, remote_dir); 
     } 
    } 

    function ftp_to_server(file_to_process_name, file_to_process_dir, remote_dir) { 
     var connection_details = conf.ftp.connections 
     do_ftp(connection_details, file_to_process_name, file_to_process_dir, remote_dir);  
    } 

    function do_ftp(connection_details, file_to_process_name, file_to_process_dir, remote_dir) { 

     var credentials = { 
      // FTP settings here 
     }; 
     var local_file = file_to_process_dir + file_to_process_name; 
     var remote_file = remote_dir + file_to_process_name; 

     connection = new sftp(credentials, function(err) { 
      if (err){ 
       throw err; 
      } 
      connection.writeFile(remote_file, fs.readFileSync(local_file, "utf8"), null, function(err) { 
       if (err) { 
        throw err; 
       } 

       console.info('FTP PUT DONE'); 

      }); 
     }); 
    }; 

回答

1

你 「連接新= SFTP(憑證,函數(ERR){」 應 var connection = new sftp(憑證,函數(錯誤){

你現在編寫的方式,「連接」是一個全局的,你正在寫它。