如何使用NodeJS下载文件

3

我希望使用NodeJS通过API下载图片文件,但问题是API链接结尾没有.jpg文件后缀,我该怎么做呢?下面是我的尝试:

url = 'https://i.pravatar.cc/225'
const https = require('https')
const fs = require('fs');


result = https.get(url, (resp) => {

        console.log('Result of response: ', resp)
        fs.writeFileSync('apiResponse', resp)
        console.log('Reached end!')
    })


当我点击URL时,它会在浏览器中显示图片,如何让我的程序将文件写入硬盘?

有很多关于它的教程可供使用。如果遇到问题,请询问。 - Piyush
在发布问题之前,你应该先搜索一下,在这里找到解决方案:https://dev59.com/CWct5IYBdhLWcg3wn-1z - Arun Saini
1
这个回答解决了你的问题吗?如何使用Node.js下载文件(不使用第三方库)? - Arun Saini
我在发布问题之前已经搜索过了,但是遇到了问题。 - Lint
4个回答

3

只需将响应写入文件即可

const url = 'https://i.pravatar.cc/225'

const https = require('https')
const fs = require('fs');

https.get(url, resp => resp.pipe(fs.createWriteStream('./test.jpeg')));

1
像魔术一样运作了,它是如何运作的?能否请您详细解释一下? - Lint
套接字是流,文件也是流。https://nodejs.org/api/stream.html - Yaroslav Gaponov
我想批量下载文件,使用相同的代码。我尝试将上面的片段放入for循环中,但它总是只下载最后一个文件。这可能是什么问题?我认为这与异步等待有关。你能指导我吗? - Lint

3

这段代码上传了几张不同的图片

const url = 'https://i.pravatar.cc/225'

const https = require('https')
const fs = require('fs');

for(let i=0; i<10; i++) 
  https.get(url, resp => resp.pipe(fs.createWriteStream(`./test_${i}.jpeg`)));

1
非常感谢您,我可以知道为什么当我把您之前回答的代码放在一个循环中时它不起作用吗? - Lint
可能你在循环中将变量i声明为var - Yaroslav Gaponov
我没有声明任何类型,只是使用了“i”,它只下载了最后一张图片,没有其他的。 - Lint
但是你是如何声明这个变量的? - Yaroslav Gaponov
1
是的,如果同步代码,但https.get是异步代码。 - Yaroslav Gaponov
显示剩余4条评论

1

请使用这个,我已经尝试过了,并且运行良好,您也可以重命名下载的文件。

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

const file = fs.createWriteStream("file.jpg");
const request = https.get("https://i.pravatar.cc/225", function(response) {
  response.pipe(file);
});

好的,我有一个略微不同的问题,有没有办法将 resp 写入文本文件或其他格式?我尝试过了,但它只显示 [object object],但是当我在控制台记录它时,它是一个庞大的对象。 - Lint

-3
尝试使用download-file库。
https://www.npmjs.com/package/download-file

安装:npm install download-file --save
var download = require('download-file')

var url = "http://i.imgur.com/G9bDaPH.jpg"

var options = {
    directory: "./images/cats/",
    filename: "cat.gif"
}

download(url, options, function(err){
    if (err) throw err
    console.log("meow")
}) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接