簡體   English   中英

Node.js-組織代碼和閉包-SFTP / Inotify

[英]Node.js - Organising code and closures - SFTP/Inotify

我希望我能就為什么我的nodejs程序表現出一些方式獲得一些建議。

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

現在我遇到的問題是,一次處理一個文件很好,但是當我一次將4個文件丟到那里時,該函數被調用了4次,但是只有一個sftp上傳通過。

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

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

  • 當“監視”目錄中發生某些事件時,將調用“ event_handler”
  • “ check_event”找出這種事件是否是我們想要的事件,在這種情況下,它是“ write”
  • “ ftp_to_server”准備連接詳細信息
  • “ do_ftp”基本上使用node-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');

            });
        });
    };

您的“連接=新sftp(憑證,功能(err){”應為var connection =新sftp(憑證,功能(err){

您當前使用的編碼方式是“連接”,它是全局的,您正在對其進行編寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM