0

I'm trying to upload a file through curl --upload-file For some reason, curl freezes and upload.backup get created empty. Any ideas how this code should be changed to make it work? I must be misunderstanding the APIs

var http = require('http'); 
var fs = require('fs');
var server = http.createServer(function(request, response) {
    var fileBackup = fs.createWriteStream("upload.backup");
    var fileBytes = request.headers['content-length'];
    var uploadedBytes = 0;
    request.on('readable', function() {
        var chunk = null;
        while (null !== (chunk = request.read())) {
            uploadedBytes += chunk.length;
            var progress = uploadedBytes / fileBytes * 100;
            response.write("progress: " + parseInt(progress, 10) + "%\n");
        }
    });
    request.pipe(fileBackup);
}).listen(8080);

1 Answer 1

1

One issue is that you're not ending your response. Secondly, you're reading the data from the request stream before it can be written to the file.

Try something like this instead:

var http = require('http'); 
var fs = require('fs');
var server = http.createServer(function(request, response) {
  var fileBackup = fs.createWriteStream('upload.backup');
  var fileBytes = parseInt(request.headers['content-length'], 10);
  var uploadedBytes = 0;
  request.pipe(fileBackup);
  if (!isNaN(fileBytes)) {
    request.on('data', function(chunk) {
      uploadedBytes += chunk.length;
      response.write('progress: ' + (uploadedBytes / fileBytes * 100) + '%\n');
    });
  }
  request.on('end', function() {
    response.end();
  });
}).listen(8080);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.