如何使用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: