在内部管道时没有结束事件"打开"

时间:2016-01-04 23:38:09

标签: node.js stream

我正在将下载文件传输到文件中,但希望确保该文件不存在。我已将代码放在此处以便更轻松地进行探索:https://tonicdev.com/tolmasky/streaming-piping-on-open-tester< - 这将显示输出(代码也在内联下方)。

所以问题是,除了完成(结束)事件之外它似乎工作正常。该文件最终在硬盘驱动器上正常运行,每个步骤都正确遵循(结构是确保没有"并行"步骤发生,这是不必要的 - 如果我有.stream(url) .pipe(fs.createWriteStream({flags:...})),即使createWriteStream返回错误,实际也会启动下载,因为文件已经存在 - 对于网络来说是不合适的。)

代码如下:

var fs = require("fs");
var got = require("got");

await download("https://www.apple.com", "./index.html");

function download(aURL, aDestinationFilePath)
{
    return new Promise(function(resolve, reject)
    {
        fs.createWriteStream(aDestinationFilePath, { flags: "wx" })
            .on("open", function()
            {
                const writeStream = this;

                console.log("SUCCESSFULLY OPENED!");

                got.stream(aURL)
                    .on("response", function(aResponse)
                    {
                        const contentLength = +aResponse.headers["content-length"] || 0;
                    console.log(aResponse.headers);
                        console.log("STARTING DOWNLOAD! " + contentLength);

                        this.on("data", () => console.log("certainly getting data"))

                        this.pipe(writeStream)                            
                            .on("error", reject)
                            .on("end", () => console.log("DONE!"))
                            .on("end", resolve);
                    })
            })
            .on("error", function(anError)
            {
                if (anError.code === "EEXIST") { console.log("oh");
                    resolve();}
                else
                    reject(anError);
            });
    });
}

1 个答案:

答案 0 :(得分:1)

根据stream docsreadable.pipe返回目标Writable流,并且在完成Writable时发出的正确事件将为Event: 'finish'