如何使用Node.js下载图像

您如何下载文件?

当我不得不以编程方式从服务器下载文件时,我问了自己这个问题。

我必须连接到服务器,下载文件,并将其存储在本地。

这是我使用的代码:

const fs = require('fs')
const request = require('request')

const download = (url, path, callback) => { request.head(url, (err, res, body) => { request(url) .pipe(fs.createWriteStream(path)) .on(‘close’, callback) }) }

const url = ‘https://…’ const path = ‘./images/image.png’

download(url, path, () => { console.log(‘✅ Done!’) })

该代码使用fs内置模块和request模块

request必须安装:

npm install request

Note that the request module was recently deprecated, which means it’s “complete” and no new changes will be applied to it. Only fixes. It doesn’t mean it will stop working and it does not mean we should stop using it.

Download my free Node.js Handbook


More node tutorials: