Response Helpers
Newgate enhances the native Node.js ServerResponse object with
a set of helper methods to make sending responses easier and more expressive.
Methods
res.status(code)
Sets the HTTP status for the response. It is a chainable method.
res.status(403).end();
res.status(400).send('Bad Request');
res.status(200).json({ success: true });
res.json(body)
Sends a JSON response. The method takes an object or array, converts it
to JSON, and sets the Content-Type header to application/json.
res.json({ name: 'Newgate', type: 'Framework' });
res.send(body)
Sends the HTTP response. The body parameter can be a Buffer
object, a String, or an Array.
res.send(Buffer.from('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.csv(data)
Sends a CSV response. It automatically sets Content-Type: text/csv.
const users = [
{ name: 'Alice', role: 'Admin' },
{ name: 'Bob', role: 'User' }
];
res.csv(users);
// Output:
// name,role
// Alice,Admin
// Bob,User
res.xml(data)
Sends an XML response. It automatically sets Content-Type: application/xml.
res.xml({ root: { message: 'Hello XML' } });
res.yaml(data)
Sends a YAML response. It automatically sets Content-Type: application/x-yaml.
res.yaml({ config: { port: 3000, debug: true } });
res.file(buffer, mimetype)
Sends a file from a buffer with the specified MIME type.
const imageBuffer = fs.readFileSync('logo.png');
res.file(imageBuffer, 'image/png');
res.download(path, [filename])
Transfers the file at path as an "attachment". Typically, browsers
will prompt the user for download.
res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.stream(readableStream)
Pipes a readable stream to the response.
const stream = fs.createReadStream('large-video.mp4');
res.stream(stream);
res.error(options)
A helper to send consistent error responses.
res.status(404).error({
message: 'User not found',
code: 404,
details: { userId: 123 }
});