-
-
Save brugnara/f9fed13dd45bd095cb764d1d4e7aa6f6 to your computer and use it in GitHub Desktop.
nodejs file transfer with http post
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 request = require('request'); | |
var path = require('path'); | |
var fs = require('fs'); | |
var filename = process.argv[2]; | |
var target = 'http://localhost:3000/upload/' + path.basename(filename); | |
var rs = fs.createReadStream(filename); | |
var ws = request.post(target); | |
ws.on('drain', function () { | |
console.log('drain', new Date()); | |
rs.resume(); | |
}); | |
rs.on('end', function () { | |
console.log('uploaded to ' + target); | |
}); | |
ws.on('error', function (err) { | |
console.error('cannot send file to ' + target + ': ' + err); | |
}); | |
rs.pipe(ws); |
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 express = require('express'); | |
var http = require('http'); | |
var path = require('path'); | |
var fs = require('fs'); | |
var app = express(); | |
app.set('port', process.env.PORT || 3000); | |
app.use(express.logger('dev')); | |
app.use(express.methodOverride()); | |
app.use(app.router); | |
app.use(express.errorHandler()); | |
app.post('/upload/:filename', function (req, res) { | |
var filename = path.basename(req.params.filename); | |
filename = path.resolve(__dirname, filename); | |
var dst = fs.createWriteStream(filename); | |
req.pipe(dst); | |
dst.on('drain', function() { | |
console.log('drain', new Date()); | |
req.resume(); | |
}); | |
req.on('end', function () { | |
res.send(200); | |
}); | |
}); | |
http.createServer(app).listen(app.get('port'), function () { | |
console.log('Express server listening on port ' + app.get('port')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment