Request

GitbookBackend2020-12-29


💡 1. small app


With piping, the two streams are connected. The data that is passed to stream 1 is also passed through stream 2 which is piped to stream 1.

import { createReadStream } from "fs";
import express from "express";
const app = express();
const readStream = createReadStream("./data.txt");

app.get("/", (req, res) => {
	readStream.pipe(res);
	setTimeout(() => {
		readStream.unpipe(res);
		res.status(200).send();
	}, 10);
});

app.listen(4000);

💡 2. pipe read to write


All things that the .pipe() method does is simply piping (passing or connecting) the readable stream to the writable one. In this way, you can e.g. transfer the data from one file to another with ease!

const readable = createReadableStreamSomehow();
const writable = createWritableStreamSomehow();
readable.pipe(writable);

💡 3. Error: write after end


app.use("/api/*/", function (req, res) {
	var url = apiUrl + req.baseUrl + req.url;
	req
		.pipe(request.post(url, { auth: { user: apiUser, pass: apiPass } }))
		.pipe(res);
});