How to download a file with Node.js (without using third-party libraries)?

后端 未结 28 1234
逝去的感伤
逝去的感伤 2020-11-22 03:37

How do I download a file with Node.js without using third-party libraries?

I don\'t need anything special. I only want to download a file from a giv

28条回答
  •  清酒与你
    2020-11-22 04:16

    ✅So if you use pipeline, it would close all other streams and make sure that there are no memory leaks.

    Working example:

    const http = require('http');
    const { pipeline } = require('stream');
    const fs = require('fs');
    
    const file = fs.createWriteStream('./file.jpg');
    
    http.get('http://via.placeholder.com/150/92c952', response => {
      pipeline(
        response,
        file,
        err => {
          if (err)
            console.error('Pipeline failed.', err);
          else
            console.log('Pipeline succeeded.');
        }
      );
    });
    

    From my answer to "What's the difference between .pipe and .pipeline on streams".

提交回复
热议问题