Ramin Mousavi
Ramin Mousavi

Reputation: 616

pipe binary file from stdout to http response

Is it possible to stream and post stdout to formData ?
This code seems to be work but not

const shell = require('shelljs')
const request = require('request')
const isStream = require('isstream')

const file = shell.exec('cat file.jpg', { silent: true, async: true })

console.log(isStream(file.stdout)) // true

const response = request
  .post({
    url,
    formData: {
    image: file.stdout
  }
}, (err, httpResponse, body) => {
    console.log(err)
})

I also tried file.stdout.pipe(PassThrough()) but not worked too

PS:

I just do this with:

cat image.jpg | curl -XPOST https://domain/process --form user_id=123456 --form image=@-

Is it possible to implement above with node ?

PS: I know there is fs.createReadStream But in real project I receive image from an external app stream file on stdout

Upvotes: 2

Views: 840

Answers (1)

Ramin Mousavi
Ramin Mousavi

Reputation: 616

I will answer my own question

const spawn = require('child_process').spawn
const ch = spawn('cat', ['./file.jpg'])

let buf = new Buffer(0)

ch.stdout
.on('data', d => {
  buf = Buffer.concat([buf, d])
})
.on('end', () => {
  send(buf)
})

function send (data) {

  request
    .post({
      url,
      formData: {
        image: {
            value: data,
            options: {
                filename: 'test.jpg'
            }
        }
      }
    }, (err, httpResponse, body) => {})
}

Upvotes: 2

Related Questions