kayasa kayasa - 2 months ago 5
Node.js Question

Upload file to servlet from node without saving it

On my node express server, I am receiving a pdf file. I am using the below code to get the pdf contents from the request

var data = new Buffer('');
request.on('data', function (chunk) {
data = Buffer.concat([data, chunk]);
});

request.on('end', function() {
console.log('PDF data is '+JSON.stringify(data));
});


Now that PDF content is available on node, I need to send it as it is to a J2EE server. In order to do that, I am first saving the PDF file in the node server, reading it from the node server and then piping it to request.post (https://github.com/request/request)

var req = require('request');

fs.writeFile('abc.pdf', data, 'binary', function(err) {
if (err) {
console.log('Error ' + JSON.stringify(err) );
throw err;
}
var source = fs.createReadStream('abc.pdf');
//send our data via POST request
source.pipe(req.post('http://'+j2ee_host+':'+j2ee_port+'/myjavaapp/Upload')
});


This works fine. However, I feel the part of saving the PDF file on the node server and then reading it is (before posting to the J2EE server using request module) is completely unnecessary, as I am not making any changes to the file.

Once I have the PDF contents in 'data' variable, I would like to directly post them to the J2EE server. However, I have not been able to find a way to use the request module to directly post file contents. I have seen some examples related to POST using request module but they refer to formData. In my case, I don't have formData but instead reading the file from request and directly posting it to the J2EE server.

Is there a way to achieve this and avoid the file write and read?

EDIT

Below is my complete code

function upload(request, response) {
var data = new Buffer('');
request.on('data', function (chunk) {
data = Buffer.concat([data, chunk]);
});

request.on('end', function () {
fs.writeFile('abc.pdf', data, 'binary', function(err){
if (err) {
console.log('Error ' + JSON.stringify(err) );
throw err;
}
var source = fs.createReadStream('abc.pdf');
source.pipe(req.post('http://'+j2ee_host+':'+j2ee_port+'/myj2eeapp/Upload'));
})
})
}

Answer

You can pipe directly from the data request to the servlet

 var req = require('request');
 function upload(request, response) {
    var target = req.post('http://'+j2ee_host+':'+j2ee_port+'/myjavaapp/Upload');
    request.pipe(target);
    target.on('finish', function () { 
      console.log('All done!');
      //send the response or make a completed callback here...
    });
  }
Comments