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.
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.
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 canpipe
data into the stream, or write directly withreq.write(data)
. Here's an example.Note, that if you use the
write
method explicitlyreq.write(data)
you must callreq.end()
. Also, the you may want to take a look at the encoding options for Node'sBuffer
(docs).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.