mikeal / bent

Functional JS HTTP client (Node.js & Fetch) w/ async await
2.2k stars 106 forks source link

How to pipe stream #112

Open robertsLando opened 4 years ago

robertsLando commented 4 years ago

I'm looking for a way to proxy requests using bent. With request it was working like:

var request = require('request');

app.use('/api', function(req, res) {
  var url = apiUrl + req.url;
  req.pipe(request(url)).pipe(res);
});
mikeal commented 4 years ago

bent returns a stream by default, but unlike request it doesn’t instrument the pipe() command to set the method and headers on a subsequent http stream, so you’ll need to do that yourself.

robertsLando commented 4 years ago

Could you show me an example on how to do this please?

Would it be possible to add the pipe method in a future relase?


Daniel

On 7 Jul 2020, at 18:47, Mikeal Rogers notifications@github.com wrote:

 bent returns a stream by default, but unlike request it doesn’t instrument the pipe() command to set the method and headers on a subsequent http stream, so you’ll need to do that yourself.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or unsubscribe.

robertoentringer commented 4 years ago

Hi @robertsLando take this example :

const fs = require('fs')
const { promisify } = require('util')
const stream = require('stream')
const pipeline = promisify(stream.pipeline)
const bent = require('bent')

const main = async () => {
  const readable = await bent('https://images.unsplash.com/photo-1595132938692-83ad2c098e47')()
  const writable = fs.createWriteStream('./image.jpg')
  await pipeline(readable, writable)
}

main()

That works for me !

czzonet commented 3 years ago

Hi @robertsLando take this example :

const fs = require('fs')
const { promisify } = require('util')
const stream = require('stream')
const pipeline = promisify(stream.pipeline)
const bent = require('bent')

const main = async () => {
  const readable = await bent('https://images.unsplash.com/photo-1595132938692-83ad2c098e47')()
  const writable = fs.createWriteStream('./image.jpg')
  await pipeline(readable, writable)
}

main()

That works for me !

Thanks, it works well in ts:

import bent from "bent";
import { createWriteStream } from "fs";
import { resolve } from "path";
import { pipeline } from "stream";
import { promisify } from "util";

const pipe = promisify(pipeline);

const URL = "http://***/1.txt";

export const run = async () => {
  const readable = (await bent(URL)("")) as NodeJS.ReadableStream;
  const writeable = await createWriteStream(resolve(__dirname, "../2.txt"));

  await pipe(readable, writeable);

  console.log("0");
};