Node.js - 组织代码和闭包 - SFTP / Inotify

时间:2012-08-22 12:26:17

标签: javascript node.js ftp sftp

我希望能就我的nodejs程序的行为方式得到一些建议。

我使用的是两个模块,node-sftp和node-inotify。我已经设置了node-inotify来查看目录并在其中写入内容时调用函数,该函数是sftp上传。

现在我遇到的问题是一次处理一个文件很好但是当我将4个文件放在一个文件夹中时,该函数被调用四次但只有一个sftp上传。

我是否需要以特定方式订购我的代码以确保sftp上传发生x次,这是否与闭包有关?

这是我的代码的基本版本......

  • 在“观看”目录
  • 上发生某些事情时调用“event_handler”
  • “check_event”指出这种类型的事件是否是我们想要的,在这种情况下它是“写”
  • “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');

            });
        });
    };

1 个答案:

答案 0 :(得分:1)

您的“connection = new sftp(凭据,功能(错误){” 应该 var connection = new sftp(credentials,function(err){

您目前对它进行编码的方式,“连接”是一个全球性的,您正在编写它。

相关问题