Below is some sample code that downloads and saves an image to your hard drive. Here are some of the reasons why it is different from your code:
- I am not sure what function
urlHtml
is, but my guess is that the rawImg
variable is actually just the src
attribute on an img
html element. If that is the case, then rawImg
is actually just a string with the image's URL in it. This is why, in my example code, I have renamed that variable in my code to be url
.
- Your function
download
expects three parameters (rawImg
, filename
, and callback
), but you only call the function with two parameters (rawImg
and a callback function). Since no filename is provided, your download function thinks that the function you intended to be a callback function is actually the filename. And since there is no third argument, callback
is undefined.
- Using the
request.head
function will only retrieve the HTTP headers without the body. So you won't actually get the image bytes with an HTTP HEAD request. See [https://ochronus.com/http-head-request-good-uses/ this article] for more details on HTTP HEAD. Since we are interested in downloading the image itself, we should perform an HTTP GET insted of an HTTP Head. This is why my sample code calls request.get
.
.on('close', function(callback) {...})
is incorrect because the on-close function will not be called with any parameters when the close
event is triggered. So callback
is undefined because it is not passed into the function when the close
event fires. This is why, in my example, there is no callback
parameter for the on-close function.
Note 1: My example code adds some require
calls for completeness, since this question is tagged as a nodejs question. It looks like you already have the fs
and request
variables in scope, so you may not need to require
them again.
Note 2: If you are getting the URL from your urlHtml('img').attr('src');
call, then replace the hardcoded url in my code with urlHtml('img').attr('src');
.
Working, example code (tested and all!!):
var fs = require('fs')
var request = require('request')
var url = 'https://avatars0.githubusercontent.com/u/5980429?v=2&s=200'
var download = function (url, filename, callback) {
request.get(url).pipe(fs.createWriteStream(__dirname + '/' + filename)).on('close', function() {
callback()
})
};
download(url, 'image.png', function () {
console.log('Image downloaded successfully. It is now saved in a file called "image.png" in the current working directory!');
});