首页 > 解决方案 > How to download a file with nodeJS

问题描述

I want to download an image file with nodeJS, by using an API, but the problem is the API link doesn't have .jpg file in the end, how do I do, below is how I am trying

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!')
    })

When I click the URL it shows the image in browser, how do make my program to write the file on hard-drive,

标签: javascriptnode.js

解决方案


只是管道响应文件

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')));

推荐阅读