LiteNode's logo

LiteNode

Docs GitHub logo
▶ Usage

Documentation

Sending a file as a response

sendFile

Description:

Sends a file as the response. This method reads the specified file from the file system, sets the appropriate Content-Type header based on the file extension, and sends the file content as the response body. It does not initiate a file download but directly displays the file content in the browser if the file type is supported.

Signature:

sendFile(filePath: string): void

Usage Examples

Sending a Text File

// Route to handle sending a text file
app.get("/text-file", (req, res) => {
    res.sendFile("/path/to/file.txt")
})

In this example, the /path/to/file.txt file will be read and sent as the response with the Content-Type header set to text/plain.

Sending an Image File

// Route to handle sending an image file
app.get("/image-file", (req, res) => {
    res.sendFile("/path/to/image.png")
})

In this example, the /path/to/image.png file will be read and sent as the response with the Content-Type header set to image/png.

Integration with Other Methods

The sendFile method can be used in conjunction with redirect and status methods to handle various response scenarios.

Using redirect with sendFile

app.get("/redirect-to-file", (req, res) => {
    res.redirect("/text-file")
})

app.get("/text-file", (req, res) => {
    res.sendFile("/path/to/file.txt")
})

In this example, a request to /redirect-to-file will redirect the client to /text-file, which then sends the file as the response.

Using status with sendFile

app.get("/file-with-status", (req, res) => {
    res.status(200).sendFile("/path/to/file.txt")
})

In this example, the status code is set to 200 before sending the file as the response.

Supported extensions

You can send files with the following extensions as a response:

Content