如何使用Node.js下载文件(不使用第三方库)?

如何在不使用第三方库的情况下使用 Node.js下载文件

我不需要什么特别的东西。我只想从给定的URL下载文件,然后将其保存到给定的目录。

LEYMandy2020/03/16 15:11:22

We can use the download node module and its very simple, please refer below https://www.npmjs.com/package/download

小胖神奇前端2020/03/16 15:11:22

Path : img type : jpg random uniqid

    function resim(url) {

    var http = require("http");
    var fs = require("fs");
    var sayi = Math.floor(Math.random()*10000000000);
    var uzanti = ".jpg";
    var file = fs.createWriteStream("img/"+sayi+uzanti);
    var request = http.get(url, function(response) {
  response.pipe(file);
});

        return sayi+uzanti;
}
逆天阿飞2020/03/16 15:11:21

也许node.js已更改,但其他解决方案似乎存在一些问题(使用节点v8.1.2):

  1. 您无需file.close()finish活动中致电默认情况下,fs.createWriteStream设置为autoClose:https ://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
  2. file.close()应该在错误时调用。删除文件(unlink()时可能不需要这样做,但通常是:https : //nodejs.org/api/stream.html#stream_visible_pipe_destination_options
  3. 临时文件未在删除 statusCode !== 200
  4. fs.unlink() 不建议不使用回调(输出警告)
  5. 如果dest文件存在;它被覆盖

下面是处理这些问题的修改后的解决方案(使用ES6和Promise)。

const http = require("http");
const fs = require("fs");

function download(url, dest) {
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(dest, { flags: "wx" });

        const request = http.get(url, response => {
            if (response.statusCode === 200) {
                response.pipe(file);
            } else {
                file.close();
                fs.unlink(dest, () => {}); // Delete temp file
                reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
            }
        });

        request.on("error", err => {
            file.close();
            fs.unlink(dest, () => {}); // Delete temp file
            reject(err.message);
        });

        file.on("finish", () => {
            resolve();
        });

        file.on("error", err => {
            file.close();

            if (err.code === "EEXIST") {
                reject("File already exists");
            } else {
                fs.unlink(dest, () => {}); // Delete temp file
                reject(err.message);
            }
        });
    });
}