download image using url in js code example
Example 1: nodejs download image from url
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
console.log('done');
});
Example 2: js get image from url
var elements = [];
function loaded(){
console.log("you have loaded an image");
}
CreateFileFrom("your/dir/here/img.png");
function CreateFileFrom(dir){
/* defining runtime variables */
var extension = dir.split('.').pop();
var keys = {"png":"IMG","jpg":"IMG","jpeg":"IMG",
"js":"SCRIPT","json":"SCRIPT",
"mp3":"AUDIO","wav":"AUDIO"};
var obj = document.createElement(keys[extension]) || {};
obj.src = dir;
/* onload function called when the resource is loaded */
obj.onload = (e) => {
elements.push(e.path[0]);
loaded()
}
/* make sure that the data is compitable */
if(keys[extension]==null){console.error("not supported media type "+extension);return;}
}