- 代码片段
const http = require('http');
const fs = require('fs');
const path = require('path');
const dest = path.join('custom_path', 'filename.extname');
// 你可能需要自行确保该路径存在
const file = fs.createWriteStream(dest);
http.get(uri, (res)=>{
if(res.statusCode !== 200){
cb(response.statusCode);
return;
}
res.on('end', ()=>{
console.log('finish download');
});
// 进度、超时等
file.on('finish', ()=>{
file.close();
}).on('error', (err)=>{
fs.unlink(dest);
});
res.pipe(file);
});
- 封装callback
const http = require('http');
const fs = require('fs');
function downloadFile(uri, dest, cb){
// 确保dest路径存在
const file = fs.createWriteStream(dest);
http.get(uri, (res)=>{
if(res.statusCode !== 200){
cb(response.statusCode);
return;
}
res.on('end', ()=>{
console.log('download end');
});
// 进度、超时等
file.on('finish', ()=>{
console.log('finish write file')
file.close(cb);
}).on('error', (err)=>{
fs.unlink(dest);
if(cb) cb(err.message);
})
res.pipe(file);
});
}
- Promise化,支持async, await调用
const http = require('http');
const fs = require('fs');
function downloadFileAsync(uri, dest){
return new Promise((resolve, reject)=>{
// 确保dest路径存在
const file = fs.createWriteStream(dest);
http.get(uri, (res)=>{
if(res.statusCode !== 200){
reject(response.statusCode);
return;
}
res.on('end', ()=>{
console.log('download end');
});
// 进度、超时等
file.on('finish', ()=>{
console.log('finish write file')
file.close(resolve);
}).on('error', (err)=>{
fs.unlink(dest);
reject(err.message);
})
res.pipe(file);
});
});
}
关注公众号“web开发圈”或扫描二维码
web开发圈二维码
发送“大会”,即可获取最新前端重要大会的视频资料。
网友评论