簡體   English   中英

管道 got.stream 到文件

[英]Piping got.stream to a file

我正在重構一些在 Node 中使用http模塊的代碼,以使用got代替。 我嘗試了以下方法:

function get(url, filePath) {
  return new Promise((resolve, reject) => {
    got.stream(url).on
        ("response", response => {
            const newFile = fs.createWriteStream(filePath);
            response.pipe(newFile);
            newFile.on("finish", () => {
              newFile.close(resolve());
            });
            newFile.on("error", err => {
              reject(err);
            });    
        }).on
        ("error", err => {
             reject(err);
        });
  });
}

finish事件從未觸發。 文件 ( filePath ) 使用 0 個字節創建。

當我使用 Node http模塊時,使用newFile的代碼塊是有效的。

pipe got.stream到文件的正確方法是什么?

根據got()文檔,您希望將 pipe stream 直接寫入您的文件,如果您使用pipeline()來執行此操作,它將收集錯誤並報告完成。

const pipeline = promisify(stream.pipeline);
const fsp = require('fs').promises;

function get(url, filePath) { 
    return pipeline(
        got.stream(url),
        fs.createWriteStream(filePath)
    );
}

// usage
get(...).then(() => {
    console.log("all done");
}).catch(err => {
    console.log(err);
});

FYI, the point of got.stream() is to return a stream that you can directly use as a stream and since you want it to go to a file, you can pipe that stream to that file. 我使用pipeline()而不是.pipe()因為 pipeline 具有比.pipe() () 更完整的錯誤處理,盡管在非錯誤條件下, .pipe()也可以工作。


如果出現錯誤,這是一個清理 output 文件的版本:

function get(url, filePath) { 
    return pipeline(
        got.stream(url),
        fs.createWriteStream(filePath)
    ).catch(err => {
         fsp.unlink(filePath).catch(err => {
             if (err.code !== 'ENOENT') {
             // trying to delete output file upon error
                 console.log('error trying to delete output file', err);
             }
         });
         throw err;
    });
}

暫無
暫無

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

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