用节点请求下载图像

嘿,我是一个真正的初学者,js节点很适合我。 我试图下载一个文件(一个图像)这是我有的代码:

function downloadFileFromURL( url, callback ) { file_name = path.basename(url); var wstream = fs.createWriteStream(file_name); wstream.on('error', function (err) { console.log(err, url); }); wstream.on( 'close', function(){ console.log( "finished downloading: ", url, this.path ); }); request(img_url).pipe( wstream ); } 

如果我用我的应用程序parsing博客提要,此function下载大约一半的图像。 我可以从浏览器中看到图片。 文件被创build,但其中一些留在0字节。

我parsing的示例Feed是: http : //feeds.feedburner.com/ButDoesItFloat?format=xml

我在这里看到这个问题: 写图像到本地服务器是相似的,并希望看到如何完成节点请求

看一下http-get来实现它。 您只需要传递两个参数,第一个是URL,第二个是保存文件的path,非常简单。 callback函数返回文件名为“result.file”。 检查下面的代码,并尝试:

 var http = require('http-get'); http.get('www.ohmydear.com/thesite.png', '/path/to/thesite.png', function (error, result) { if (error) { console.error(error); } else { console.log('File downloaded at: ' + result.file); } });