如何使用Node.js下載並保存圖片

我曾經需要從互聯網上下載文件,而且還想使用await以簡單的方式在完成後做其他事情。 您可以使用Axios達到這個目的。 import axios from 'axios' 然後寫一個像這樣的download()函數: async function download(url, filepath) { const response = await axios({ url, method: 'GET', responseType: 'stream', }) return new Promise((resolve, reject) => { response.data .pipe(fs.createWriteStream(filepath)) .on('error', reject) .once('close', () => resolve(filepath)) }) } 然後使用以下方式調用: const remote_url = 'https://...' const local_path = './images/test.png' await download(remote_url, local_path)