Created
October 14, 2014 16:14
-
-
Save adohe-zz/b8b16c70a712715457db to your computer and use it in GitHub Desktop.
add upload script
This file contains 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 http = require('http'), | |
fs = require('fs'), | |
parse = require('url').parse; | |
function upload(url, filePath, callback) { | |
var urlObj = parse(url), | |
path = urlObj.pathname + (urlObj.search || ''), | |
options = { | |
hostname: urlObj.hostname, | |
path: path, | |
port: urlObj.port || 80, | |
method: 'GET' | |
}; | |
var req = http.request(options, function(res) { | |
res.setEncoding('utf-8'); | |
var chunks = [], | |
length = 0; | |
res.on('data', function(chunk) { | |
chunks.push(chunk); | |
length += chunk.length; | |
}).on('end', function() { | |
var buffer = new Buffer(length); | |
for(var i, pos = 0, l = chunks.length; i < l; i++) { | |
chunks[i].copy(buffer, pos); | |
pos += chunks[i].length; | |
} | |
res.body = buffer; | |
callback(null, res); | |
}); | |
}); | |
var rs = fs.createReadStream(filePath); | |
rs.on('data', function(data) { | |
req.write(data); | |
}).on('end', function() { | |
req.end(); | |
}); | |
} | |
function upload_with_pipe(url, filePath, callback) { | |
var urlObj = parse(url), | |
path = urlObj.pathname + (urlObj.search || ''), | |
options = { | |
hostname: urlObj.hostname, | |
path: path, | |
port: urlObj.port || 80, | |
method: 'GET' | |
}; | |
var req = http.request(options, function(res) { | |
res.setEncoding('utf-8'); | |
var chunks = [], | |
length = 0; | |
res.on('data', function(chunk) { | |
chunks.push(chunk); | |
length += chunk.length; | |
}).on('end', function() { | |
var buffer = new Buffer(length); | |
for(var i, pos = 0, l = chunks.length; i < l; i++) { | |
chunks[i].copy(buffer, pos); | |
pos += chunks[i].length; | |
} | |
res.body = buffer; | |
callback(null, res); | |
}); | |
}); | |
// pipe | |
fs.createReadStream(filePath).pipe(req); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment