Skip to content

Instantly share code, notes, and snippets.

@ryanlid
Last active June 3, 2018 17:02
Show Gist options
  • Save ryanlid/e1fd4d38ac616362fc5047cdfa5cd0e5 to your computer and use it in GitHub Desktop.
Save ryanlid/e1fd4d38ac616362fc5047cdfa5cd0e5 to your computer and use it in GitHub Desktop.
node下载文件资源
var fs = require('fs')
var http = require('http');
var https = require('https');
/**
* @param {String} url 下载链接
* @param {String} localFile 本地保存路径
* @param {function} callback
*/
function getfile(url, localFile, callback) {
var httpClient = url.slice(0, 5) === 'https' ? https : http;
var stream = fs.createWriteStream(localFile);
stream.on('finish', function () {
callback(localFile);
});
httpClient.get(url, function (image) {
image.pipe(stream);
});
}
getfile('https://www.baidu.com/img/bd_logo1.png', './img/baidu.png', function () {
console.log('下载完成,执行其他操作')
})
var superagent = require('superagent');
var fs = require('fs')
// 通过superagent 下载文件
/**
* @param {String} url 下载链接
* @param {String} localFile 本地保存路径
* @param {function} callback
*/
function getfile(url, localFile, callback) {
var stream = fs.createWriteStream(localFile)
var image = superagent.get(url)
image.pipe(stream)
image.on('end', function () {
callback(localFile)
})
}
getfile('https://www.baidu.com/img/bd_logo1.png', './img/baidu.png', function (localFile) {
console.log('下载完成,执行其他操作')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment