Node.js下载图片
使用了request来作为请求图片数据 将图片保存到本地
var path = require ( 'path' ) ;
var fs = require ( 'fs' ) ;
var request = require ( 'request' ) ;
let imgUrl = 'http://img.jpg' ;
function downloadFile ( imgPath, callback) {
let fileName = path. basename ( imgPath) ;
let fileDownloadPath = './image' + fileName;
let exist = fs. existsSync ( fileDownloadPath) ;
if ( ! exist) {
let writeStream = fs. createWriteStream ( fileDownloadPath) ;
let readStream = request ( imgPath) ;
readStream. pipe ( writeStream) ;
readStream. on ( 'end' , function ( ) {
readStream. end ( ) ;
callback ( null , 'success' ) ;
} ) ;
readStream. on ( 'error' , function ( error) {
writeStream. end ( ) ;
fs. unlinkSync ( fileDownloadPath) ;
readStream. end ( ) ;
callback ( null , 'fail' ) ;
setTimeout ( ( ) => {
bagpipe. push ( downloadFile, imgPath, function ( err, data) {
} ) ;
} , 5000 ) ;
} )
writeStream. on ( "finish" , function ( ) {
readStream. end ( ) ;
writeStream. end ( ) ;
} )
. on ( 'error' , function ( err) {
readStream. end ( ) ;
writeStream. end ( ) ;
} ) ;
} else {
console. log ( 'this file is existed' ) ;
}
}
var Bagpipe = require ( 'bagpipe' ) ;
var bagpipe = new Bagpipe ( 100 ) ;
let imgList = [ imgUrl, imgUrl, ... ] ;
imgList. foreach ( path => {
bagpipe. push ( downloadFile, path, function ( err, data) {
} ) ;
} ) ;