Express Response Options

In Express.js, res.send() is used to send a response to the client. While it’s commonly used to send strings, it can also send several other types of data. Here are the main options you can use with res.send() and some alternatives:


res.send() accepts:

Data TypeDescription
StringSends plain text or HTML: res.send("Hello World")
BufferSends binary data: res.send(Buffer.from('hello'))
Object / ArrayAutomatically JSON-stringified: res.send({ message: 'OK' })
null / undefinedSends an empty response (status 204)

Alternative methods:

MethodUse Case
res.json(data)Sends JSON response with proper Content-Type: application/json
res.status(code)Sets HTTP status code: res.status(404).send("Not Found")
res.sendFile(path)Sends a file: res.sendFile(__dirname + '/index.html')
res.download(path)Sends a file as an attachment (download prompt)
res.redirect(url)Redirects the client to a different URL
res.end()Ends the response without sending any data

Example:

app.get('/example', (req, res) => {
  res.status(200).json({ success: true, message: "Data sent!" });
});

res as writable stream

res is a writeable stream in itself

To read a file in Express and send it as a stream, you can use Node.js’s built-in fs.createReadStream() along with res (which is a writable stream itself).

Here’s a basic example of how to do it:


Example: Stream a file (e.g., PDF, image, or large text file)

const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();

app.get('/download', (req, res) => {
  const filePath = path.join(__dirname, 'files/sample.pdf'); // or .txt, .png, etc.
  
  // Set headers (optional, but helpful)
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'inline; filename="sample.pdf"'); // or attachment for download

  // Create and pipe the stream
  const fileStream = fs.createReadStream(filePath);
  
  fileStream.on('error', (err) => {
    res.status(500).send('File not found or cannot be read.');
  });

  fileStream.pipe(res); // Stream directly to client
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

Key Points:

  • fs.createReadStream() avoids loading the full file into memory.
  • res is a writable stream, so fileStream.pipe(res) works perfectly.
  • You can set headers like Content-Type or Content-Disposition based on your use case.