Skip to content

Instantly share code, notes, and snippets.

@jacky810124
Last active August 29, 2015 14:19
Show Gist options
  • Save jacky810124/1e4330b0426ce3f93f90 to your computer and use it in GitHub Desktop.
Save jacky810124/1e4330b0426ce3f93f90 to your computer and use it in GitHub Desktop.
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
/*var targetURL = process.argv[2] || null;*/
var targetURL = 'http://www.stust.edu.tw/';
if (!targetURL) {
process.exit();
}
//解析URL
var urlObj = url.parse(targetURL);
var req = http.request({
hostname: urlObj.hostname,
path: urlObj.path,
method: 'GET'
}, function (res) {
//解析網址路徑,並取得檔案名稱
var filename = path.basename(urlObj.path);
//判斷檔案是否存在
fs.exists(filename, function (exists) {
if (exists) {
fs.unlink(filename, function (err) {
if (err)
console.log(err);
saveFile();
});
return;
}
saveFile();
});
function saveFile() {
//收到資料
res.on('data', function (chunk) {
console.log('Downloading');
fs.appendFile(filename, chunk, function () {
res.on('end', function (chunk) {
console.log('Finished');
process.exit();
});
});
});
}
});
events.js:85
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:746:11)
at TCP.onread (net.js:559:26)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment