6

I need to stream files from a client (nodejs command line) and a server (express nodejs).

This is the client side:

var request = require('request');
var fs = require('fs');

// ...

  var readStream = fs.createReadStream(file.path);
  readStream.on('end', function() {
    that.emit('finished');
  });
  readStream.pipe(request.post(target));

// ...

This is the server side:

var fs = require('fs');
var path = require('path');

// ...

    app.post('/:filename', function(req, res) {
      req.setEncoding('binary');
      var filename = path.basename(req.params.filename);
      filename = path.resolve(destinationDir, filename);
      var dst = fs.createWriteStream(filename);
      req.pipe(dst);
      req.on('end', function() {
        res.send(200);
      });
    });

// ...

All is working, files are saved correctly on the server side... but they are about 50% bigger than the source files. I tried to see difference between the two files with hexdump and the server side file has similar content but with 0xC2 sometimes. I guess this is related to encoding.

5
  • 1
    Why do you set the encoding? This will convert every single chunk into strings and is mainly intended if you want to read strings from the stream. As you directly pipe the request to a file, I don't think you should be calling setEncoding. Commented Nov 20, 2013 at 17:19
  • try fs.createWriteStream(filename, {encoding: 'binary'}) Commented Nov 20, 2013 at 17:21
  • fs.createWriteStream(filename, {encoding: 'binary'}) didn't work. Node api: The encoding can be 'utf8', 'ascii', or 'base64' Commented Nov 20, 2013 at 17:24
  • 1
    Removing 'req.setEncoding('binary');` is the solution. Strange... I added it when it wasn't working Commented Nov 20, 2013 at 17:26
  • Good to know! Will add this as an answer so that the solution will be easier to find. Commented Nov 20, 2013 at 17:57

1 Answer 1

3

Don't call req.setEncoding('binary').

This will convert every single chunk into strings and is mainly intended if you want to read strings from the stream. As you directly pipe the request to a file, you don't need to do it.

Sign up to request clarification or add additional context in comments.

4 Comments

Also it's worth mentioning that binary encoding is deprecated.
This isn't mentioned in the documentation. The source code mentions backwards compatibility, but not deprecation. Do you have a link?
Which refers to this issue, looks like binary won't go away soon...
Well, I think one can tell that binary is a little deprecated, but not deprecated-deprecated) Anyway, it's not a good idea to use it in new code.

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.