Last active
June 3, 2018 17:02
-
-
Save ryanlid/e1fd4d38ac616362fc5047cdfa5cd0e5 to your computer and use it in GitHub Desktop.
node下载文件资源
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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('下载完成,执行其他操作') | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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