9

ここに私のコードのスニペットがあります:

var processListing = function (directoryItems) {
    console.log('foreach');
    var itemsToDownload = [];
    directoryItems.forEach(function (element, index, array) {
        //Ignore directories
        if (element.type === 'd') {
            console.log('directory ' + element.name);
            return;
        }
        //Ignore non zips
        if (path.extname(element.name) !== '.zip') {
            console.log('ignoring ' + element.name);
            return;
        }
        //Download zip
        itemsToDownload.push({
            source: element.name,
            destination: element.name
        });
        //aftpSystem.downloadFile(element.name, element.name);
    });
    console.log('after foreach');
    return itemsToDownload;
};

var getFiles = function () {
    console.log('got files');
    return fs.readdirAsync(process.cwd() + "/zips/").then(function (files) {
        return files.filter(function (filename) {
            return path.extname(filename) === '.zip';
        });
    });
};

    aFtpClient. //this has been promisified
    listAsync(). //so calls methodAsync
    then(processListing).
    map(function (object) {
        return processItem(object).then(function (processResult) {
            return {
                input: object,
                result: processResult
            };
        });
    }).
    map(function (downloadItem) {
        console.log('downloading files');

        downloadItem.result.once('close', function () {
            console.log('closed');
        });

        return downloadItem.result.pipe(fs.createWriteStream(process.cwd() + "/zips/" + downloadItem.input.destination));
    }).
    then(getFiles).

Promise を使用して FTP 経由でアイテムをダウンロードしようとしています。現時点では、最初のファイルをダウンロードしますが、後続のファイルでは失敗します。私はノードを初めて使用しますが、2番目のマップ関数が約束を返す必要があることはかなり確信していますが、何度も試行した後、どのように解決することができませんでした. 約束のために使用bluebirdしていますが、それとストリームを操作する方法がわかりません。

正しい方向に私を向けることができますか?

ありがとう

4

2 に答える 2

2

これが約束されたパイプです:

//example: promisified_pipe(foo, fs.createWriteStream(somepath))enter code here
function promisified_pipe(response, file) {
let ended = false;

return new Promise(function(resolve, reject) {
    response.pipe(file);

    function nice_ending() {
      if (!ended) {
        ended = true;
        resolve();
      }
    }

    function error_ending() {
      if (!ended) {
        ended = true;
        reject("file error");
      }
    }

    file.on('finish', nice_ending);
    file.on('end', nice_ending);
    file.on('error', error_ending);
    file.on('close', error_ending);
  }).finally(() => file.close())
}
于 2016-06-14T03:27:12.680 に答える