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

后端 未结 28 1775
逝去的感伤
逝去的感伤 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:18

    You can create an HTTP GET request and pipe its response into a writable file stream:

    const http = require('http');
    const fs = require('fs');
    
    const file = fs.createWriteStream("file.jpg");
    const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
      response.pipe(file);
    });
    

    If you want to support gathering information on the command line--like specifying a target file or directory, or URL--check out something like Commander.

提交回复
热议问题