LiteNode's logo

LiteNode

Docs GitHub logo
▶ Usage

Documentation

Response Methods

LiteNode extends the native Node.js response object with several convenient methods for sending different types of content. These methods simplify the process of setting appropriate headers and sending properly formatted responses to clients.

Overview

The following response methods are available:

Each of these methods can be used in various combinations to create flexible and powerful response handling in your routes.

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

Parameters:

Returns: 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.

Supported Extensions

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

Files that can be rendered in browser:

For downloads:

txt

Description: The txt method sets the Content-Type header to text/plain and sends the provided plain text as the response body. This method simplifies the process of returning plain text responses to the client.

Signature:

txt(text: string): void

Parameters:

Returns: void

Example:

// Route to handle sending plain text response
app.get("/plaintext", (req, res) => {
    res.txt("This is a plain text response.")
})

In this example, the /plaintext route will send the plain text response "This is a plain text response." to the client.

html

Description: The html method sets the Content-Type header to text/html and sends the provided HTML content as the response body. This method simplifies the process of returning HTML responses to the client.

Signature:

html(html: string, statusCode?: number): void

Parameters:

Returns: void

Example:

// Route to handle sending HTML response
app.get("/html-page", (req, res) => {
    res.html("<h1>Welcome to the HTML page</h1>")
})

In this example, the /html-page route will send the HTML response <h1>Welcome to the HTML page</h1> to the client.

xml

Description: The xml method sets the Content-Type header to application/xml and sends the provided XML content as the response body. This method ensures that XML content is correctly handled and returned to the client. This is particularly useful for API endpoints or responses where XML is the desired format, such as RSS feeds and sitemaps.

Signature:

xml(xmlContent: string, statusCode?: number): void

Parameters:

Returns: void

Example:

// Route to handle sending XML response
app.get("/xmlresponse", (req, res) => {
    const xmlContent = `
        <response>
            <message>This is an XML response</message>
        </response>
    `
    res.xml(xmlContent)
})

In this example, the /xmlresponse route will send the XML response to the client.

json

Description: The json method sets the Content-Type header to application/json and sends the provided data as a JSON-formatted response body. This method automatically converts JavaScript objects to JSON strings.

Signature:

json(data: any): void

Parameters:

Returns: void

Example:

// Route to handle sending JSON response
app.get("/api/users", (req, res) => {
    const users = [
        { id: 1, name: "Alice" },
        { id: 2, name: "Bob" },
    ]
    res.json(users)
})

In this example, the /api/users route will send the users array as a JSON response to the client.

redirect

Description: The redirect method redirects the client to the specified location with an optional status code. The default status code is 302 (Found), which is a temporary redirect.

Signature:

redirect(location: string, statusCode?: number): void

Parameters:

Returns: void

Example:

// Route to handle redirection
app.get("/old-page", (req, res) => {
    res.redirect("/new-page", 301) // Permanent redirect
})

In this example, the /old-page route will redirect the client to /new-page with a status code of 301 (Moved Permanently).

status

Description: The status method sets the HTTP status code for the response and returns the response object for chaining with other methods.

Signature:

status(code: number): this

Parameters:

Returns: The response object for method chaining.

Example:

// Route to handle a request with custom status code
app.get("/not-found", (req, res) => {
    res.status(404).txt("The requested resource was not found.")
})

In this example, the /not-found route will send a response with status code 404 and the message "The requested resource was not found."

Combining Response Methods

Most of these methods can be combined with the status method for more flexible response handling.

Examples of Combined Response Methods

Status with HTML

app.get("/error-page", (req, res) => {
    res.status(500).html("<h1>Internal Server Error</h1><p>Please try again later.</p>")
})

In this example, the /error-page route will send an HTML response with a status code of 500.

Status with JSON

app.get("/api/resource-not-found", (req, res) => {
    res.status(404).json({ error: "Resource not found", code: 404 })
})

In this example, the /api/resource-not-found route will send a JSON response with a status code of 404.

Redirect After Form Submission

app.post("/submit-form", (req, res) => {
    // Process form data
    // ...

    // Redirect to success page
    res.redirect("/success")
})

In this example, after processing the form data submitted to /submit-form, the user will be redirected to the /success page.

Error Handling with Response Methods

Response methods can be used effectively in error handlers to provide appropriate responses based on the error type.

app.onError((error, req, res) => {
    if (error.type === "not_found") {
        res.status(404).html("<h1>404 - Not Found</h1><p>The requested resource could not be found.</p>")
    } else if (error.type === "unauthorized") {
        res.status(401).json({ error: "Unauthorized", message: "Please log in to access this resource." })
    } else {
        res.status(500).html("<h1>500 - Internal Server Error</h1><p>Something went wrong. Please try again later.</p>")
    }
})

In this example, the error handler uses different response methods based on the type of error encountered.

Best Practices

  1. Use the appropriate response method for the content type you're sending:

    • sendFile() for file content
    • txt() for plain text
    • html() for HTML content
    • xml() for XML data
    • json() for JSON data
  2. Set appropriate status codes using the status() method to indicate the outcome of the request.

  3. Use redirects carefully and consider whether a temporary (302) or permanent (301) redirect is appropriate.

  4. Handle errors gracefully by using appropriate status codes and informative error messages.

  5. Consider content negotiation for APIs that might need to respond with different content types based on client preferences.

Content