简体   繁体   English

管道 got.stream 到文件

[英]Piping got.stream to a file

I am refactoring some code that was using http module in Node to use got instead.我正在重构一些在 Node 中使用http模块的代码,以使用got代替。 I tried the following:我尝试了以下方法:

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);
        });
  });
}

The finish event never fired. finish事件从未触发。 The file ( filePath ) is created with 0 bytes.文件 ( filePath ) 使用 0 个字节创建。

The block of code using newFile was something that worked when I was using the Node http module.当我使用 Node http模块时,使用newFile的代码块是有效的。

What is the proper way to pipe got.stream to a file? pipe got.stream到文件的正确方法是什么?

Per the got() documentation , you want to pipe the stream directly to your file and if you use pipeline() to do it, it will collect errors and report completion.根据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. 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. I use pipeline() instead of .pipe() because pipeline has much more complete error handling that .pipe() , though in non-error conditions, .pipe() would also work.我使用pipeline()而不是.pipe()因为 pipeline 具有比.pipe() () 更完整的错误处理,尽管在非错误条件下, .pipe()也可以工作。


Here's a version that cleans up the output file if there's an error:如果出现错误,这是一个清理 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