Appearance
write
Writes content to the response body in a MARS Engine handler.
Syntax
js
write('key', 'text') // Writes a JSON response object {key: 'text'}
write(image); // If 'image' is a binary file writes the binary data with appropriate headers (eg. image/png, image/jpeg)
write('data', obj) // Serializes obj to JSON and returns it under the key 'data'Details
The write function sets the response body for the current request.
- Accepts strings, objects or binary.
- If an object is passed, MARS Engine automatically serializes it to JSON and sets the
Content-Typeheader toapplication/json. - If binary data is passed, it is written directly with no transformation trying to set the appropriate
Content-Type. - Subsequent calls to
writedo not overwrite previous calls, they append if possible. Eg. You can't respond with two files in one response, so calling write twice leads to improper formatting.
Supported Types
| Input Type | Behavior | Content-Type set |
|---|---|---|
string | Sends JSON text under the key 'unset key' | application/json |
Buffer | Sends raw binary data | As appropriate |
object | Serializes to JSON | application/json |
Examples
Plain text response
js
response.setContentType('text/plain')
write('Hello, world!')JSON response
js
write({ message: 'Success', userId: 42 })Binary response
js
const image = fs.read("path/to/image.png")
write(image.data)Text response with suggested filename
js
const csvData = "John,Doe,1980\nMary,Jane,1990"
response.setContentType('text/csv')
response.header("Content-Disposition", 'attachment;filename="data_export.csv"');
write(csv)Combined with status
js
response.status(201)
write({ status: 'created', id: 42 })Notes
- You can use
write()multiple times per request; it will append to any previous content if possible - Pair with
response.status()andheader()for full response control.