Node.js HTTP Response Builder

5.0.1 · maintenance · verified Tue Apr 21

node-res is a lightweight Node.js module designed to simplify the creation of HTTP responses by providing a facade over the native `http.ServerResponse` object. It offers utility methods to easily set common HTTP headers, define response statuses, and automatically determine appropriate `Content-Type` headers based on the body content. As of its latest stable version `5.0.1`, published over seven years ago in August 2018, the library appears to be in a maintenance-only state with no active development or regular release cadence. Its key differentiator is its minimal footprint and focus on direct manipulation of the response object without introducing significant abstraction layers, offering helpers for common tasks like sending HTML, JSON, or JSONP, and handling ETags. It is primarily built for CommonJS environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to set up a basic Node.js HTTP server and use `node-res` to send different types of responses (HTML, JSON, custom status messages, and JSONP) with automatic content-type handling.

const http = require('http');
const nodeRes = require('node-res');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    // Send a simple HTML response with status 200
    nodeRes.send(req, res, '<h1>Hello from node-res!</h1>');
  } else if (req.url === '/json') {
    // Send a JSON response with status 200
    nodeRes.send(req, res, { message: 'This is a JSON response', timestamp: Date.now() });
  } else if (req.url === '/error') {
    // Send a custom status (500) and message
    nodeRes.send(req, res, 'Something went wrong!', 500);
  } else if (req.url.startsWith('/jsonp')) {
    // Send a JSONP response, expecting '?callback=myCallback' query parameter
    const callbackFn = new URLSearchParams(req.url.split('?')[1]).get('callback') || 'callback';
    nodeRes.jsonp(req, res, { data: 'JSONP data from node-res' }, callbackFn);
  } else {
    // 404 Not Found response
    nodeRes.send(req, res, 'Not Found', 404);
  }
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Try visiting:');
  console.log(`- http://localhost:${PORT}/`);
  console.log(`- http://localhost:${PORT}/json`);
  console.log(`- http://localhost:${PORT}/error`);
  console.log(`- http://localhost:${PORT}/jsonp?callback=myCallbackFunction`);
});

view raw JSON →