2

I've got an audio file which I post to a server for translation. I've managed to create a request in postman, but I do not know how to write the file to this server. Below is the code I have got so far:

var http = require("https");

var options = {}

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
   });
});

options{} is filled with method/hostname/port ofcourse. In postman I add "binary" file, but I cannot figger out how to write a file to the request in Node JS.

1

3 Answers 3

4

One solution that would easily fit into your current program without too much work is to make use of the form-data module on npm.

The form-data module makes ease of multipart requests in node. The following is a simple example of how to use.

var http = require("https");
var FormData = require('form-data');
var fs = require('fs')

var form = new FormData();
form.append('my_field', fs.createReadStream('my_audio.file'));

var options = {
  host: 'your.host',
  port: 443,
  method: 'POST',
  // IMPORTANT!
  headers: form.getHeaders()
}

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
   });
});

// Pipe form to request
form.pipe(req);

In a "real-world" scenario you would want to do a lot more error checking. Also, there are plenty of other http clients on npm that make this process easy as well (the request module uses form-data BTW). Check out request, and got if you are interested.

For sending a binary request the fundamentals are still the same, req is a writable stream. As such, you can pipe data into the stream, or write directly with req.write(data). Here's an example.

var http = require('https');
var fs = require('fs');

var options = {
  // ...
  headers: {
    'Content-Type': 'application/octet-stream'
  }
}

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
   });
});


var audioFile = fs.createReadStream('my_audio.file', { encoding: 'binary' });
audioFile.pipe(req);

Note, that if you use the write method explicitly req.write(data) you must call req.end(). Also, the you may want to take a look at the encoding options for Node's Buffer (docs).

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

4 Comments

Thank you for the help. unfortunately, the server I am posting to does not accept form-data, only binary file transfer.
Sorry, I misunderstood. I edited the answer, hope it helps.
Thank you, this is the solution for me
Thanks "var body = Buffer.concat(chunks);" really worked for me!
1

Thanks @undefined, your answer really helped me.

I am posting my solution which worked for me to send file to another server using axios. Ignore the type specifications, I had Typescript enabled for my project.

export const fileUpload: RequestHandler = async (req: Request, res: Response, next: NextFunction) => {
    const chunks: any[] = [];
    req.on('data', (chunk) => chunks.push(chunk));
    req.on('end', () => {
        const data = Buffer.concat(chunks);
        axios.put("ANOTHER_SERVER_URL", data).then((response) => {
            console.log('Success', response);
        }).catch(error => {            
            console.log('Failure', error);
        });
    });
    return res.status(200).json({});
};

Thanks, hope it helps!

Comments

-1

You can use the request package on npm.

Install the request module from npm: npm install request --save

Then use the request module to send your request.

Have a look at https://www.npmjs.com/package/request for details on implementation.

1 Comment

Give a real example. Right now it is just a comment

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.