How do you send data back through the same stream

How do you send data back in the same stream? Like for a request response pattern.

This is what I have come up with. Is there a better way to do this?
Here I need to keep track of the requests I have sent and to whom and then get a proper response back.

let handler = ({connection, stream}) =>{
         await pipe(stream, async (src) => {
                  for await (const msg of src) {
                      let data = JSON.parse(msg);
                      if(data.type == "REQUEST"){
                              let res = json.stringify(process_func(data))
                              pipe(res, stream)
                     }
                    if(data.type == "RESPONSE" && checkIfIHaveRequestedThisData){
                               //output data
                    }
             }
          });
}
node1.handle('/rpcservice',handler)
node2.handle('/rpcservice',handler)

let { stream } = await node1.dialProtocol(node2, '/rpcservice')
let reqObj = { type : "REQUEST", body : "Foo" }

pipe(JSON.stringify(reqObj), stream)

//CC @vasco-santos for js-libp2p.

Hey @sahilpohare

There are a couple of examples you can have a look. Echo example seems to do what you would like. But chat is also a nice example. If you would like to go through a more detailed example, this is really complete chat example: GitHub - libp2p/js-libp2p-examples: Examples for the JS implementation of libp2p

Using pipe facilitates interacting with async iterables, but it also requires that you understand exactly how they work. You can also start with lower level primitives if it is helpful like using it-pushable module. Or you can create a stream handler like this and expose read and write. Either way, I recommend that you use it-pipe whenever possible, otherwise it is really easy to get into bad situations by not properly closing streams in the end.