Prabhat kr. Prabhakar
Prabhat kr. Prabhakar

Reputation: 31

How to pipe stream data from file to the post body request in node js

I would like to pass a readable stream to the post request body using pipe, but am having trouble. This is the code I have:

var request = require('request');  
var fs = require('fs');   
var source = fs.createReadStream('./originalJsonDataWithObject.json');  //creating a read stream to read the file 
    source.pipe(request.post('http://localhost:3030/decompress'));  //piping it to the post request

Upvotes: 3

Views: 7636

Answers (1)

V. Smt
V. Smt

Reputation: 25

var request = require('request');
var fs = require('fs');
var file = fs.createReadStream('./originalJsonDataWithObject.json');
var req = request.post({
  url: 'your post url',
  headers: {<headers>},
  body: file
});

POST request body parameter is the data you are actually sending with your request. This data can be in many forms (stream, buffer, string etc.) You do not need to pipe it. If you need to post JSON data, you can do this:

    const req = request.post({
        url: 'http://localhost:3030/decompress',  
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(<your JSON data>)                
    });

Upvotes: 1

Related Questions